开发者

Groovy: indexes of substrings?

开发者 https://www.devze.com 2023-04-09 22:23 出处:网络
How do I find the indexes of all the occuran开发者_高级运维ces of a substring in a large string -

How do I find the indexes of all the occuran开发者_高级运维ces of a substring in a large string - (so basically ,and extension of the "indexOf" function) . Any ideas?

Current situation:

def text  = " --- --- bcd -- bcd ---" 
def sub = "bcd"
text.indexOf(sub) 
// = 9

I want something like:

def text  = " --- --- bcd -- bcd ---" 
def sub = "bcd"
text.indexesOf(sub) 
// = [9,15]

Is there such a function? How should I implement it otherwise? (in a non trivial way)


You could write a new addition to the String metaClass like so:

String.metaClass.indexesOf = { match ->
  def ret = []
  def idx = -1
  while( ( idx = delegate.indexOf( match, idx + 1 ) ) > -1 ) {
    ret << idx
  }
  ret
}

def text  = " --- --- bcd -- bcd ---" 
def sub = "bcd"
text.indexesOf(sub) 

There is nothing I know of that exists in groovy currently that gets you this for free though


This is a relatively easy approach:

String.metaClass.indexesOf = { arg ->
  def result = []
  int index = delegate.indexOf(arg)
  while (index != -1) {
    result.add(index);
    index = delegate.indexOf(arg, index+1);
  }
  return result;
}

Note that this will find overlapping instances (i.e. "fooo".indexesOf("oo") will return [1, 2]). If you don't want this, replace index+1 with index+arg.length().

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号