Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy: indexes of substrings?

Tags:

groovy

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)

like image 931
Yossale Avatar asked Dec 28 '25 06:12

Yossale


2 Answers

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

like image 119
tim_yates Avatar answered Dec 30 '25 22:12

tim_yates


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

like image 41
Joachim Sauer Avatar answered Dec 30 '25 23:12

Joachim Sauer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!