I don't know anything that currently exists, but you can add this method to metaClass from String if you want ... Something like:
String.metaClass.allIndexOf { pat -> def (ret, idx) = [ [], -2 ] while( ( idx = delegate.indexOf( pat, idx + 1 ) ) >= 0 ) { ret << idx } ret }
Which can be called:
"Finds all occurrences of a regular expression string".allIndexOf 's'
and returns (in this case)
[4, 20, 40, 41, 46]
Edit
Actually ... a version that can work with regex options will be:
String.metaClass.allIndexOf { pat -> def ret = [] delegate.findAll pat, { s -> def idx = -2 while( ( idx = delegate.indexOf( s, idx + 1 ) ) >= 0 ) { ret << idx } } ret }
which can then be called as:
"Finds all occurrences of a regular expression string".allIndexOf( /a[lr]/ )
:
[6, 32]
Edit 2
And finally, this code as a category
class MyStringUtils { static List allIndexOf( String str, pattern ) { def ret = [] str.findAll pattern, { s -> def idx = -2 while( ( idx = str.indexOf( s, idx + 1 ) ) >= 0 ) { ret << idx } } ret } } use( MyStringUtils ) { "Finds all occurrences of a regular expression string".allIndexOf( /a[lr]/ ) }
source share