Groovy:有没有办法将所有出现的String作为整数偏移列表返回?

Sea*_*oyd 4 java string groovy

给定一个String,我知道Groovy提供了方便的方法
String.findAll(String, Closure)

查找String中所有出现的正则表达式字符串.任何匹配都将传递给指定的闭包.预计闭包将在第一个参数中具有完全匹配.如果有任何捕获组,它们将被放置在后续参数中.

但是,我正在寻找一种类似的方法,其中闭包接收Matcher对象或匹配的int偏移量.有这样的野兽吗?

或者,如果不是:是否有一种常见的方法可以将给定字符串或模式的所有匹配的偏移量作为集合或整数/整数数组返回?(Commons/Lang或Guava都可以,但我更喜欢普通的Groovy).

tim*_*tes 5

我不知道当前存在的任何东西,但如果你想要的话,你可以将方法添加到String的metaClass ...类似于:

String.metaClass.allIndexOf { pat ->
  def (ret, idx) = [ [], -2 ]
  while( ( idx = delegate.indexOf( pat, idx + 1 ) ) >= 0 ) {
    ret << idx
  }
  ret
}
Run Code Online (Sandbox Code Playgroud)

可以通过以下方式调用:

"Finds all occurrences of a regular expression string".allIndexOf 's'
Run Code Online (Sandbox Code Playgroud)

并返回(在这种情况下)

[4, 20, 40, 41, 46]
Run Code Online (Sandbox Code Playgroud)

编辑

实际上......可以使用正则表达式参数的版本是:

String.metaClass.allIndexOf { pat ->
  def ret = []
  delegate.findAll pat, { s ->
    def idx = -2
    while( ( idx = delegate.indexOf( s, idx + 1 ) ) >= 0 ) {
      ret << idx
    }
  }
  ret
}
Run Code Online (Sandbox Code Playgroud)

然后可以这样调用:

"Finds all occurrences of a regular expression string".allIndexOf( /a[lr]/ )
Run Code Online (Sandbox Code Playgroud)

给:

[6, 32]
Run Code Online (Sandbox Code Playgroud)

编辑2

最后这个代码作为一个类别

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]/ )
}
Run Code Online (Sandbox Code Playgroud)