Yossale
Yossale

Reputation: 14361

Groovy: indexes of substrings?

How do I find the indexes of all the occurances 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)

Upvotes: 3

Views: 10262

Answers (2)

tim_yates
tim_yates

Reputation: 171084

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

Upvotes: 7

Joachim Sauer
Joachim Sauer

Reputation: 308021

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().

Upvotes: 6

Related Questions