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

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

Finds all occurrences of a regular
expression string within a String. Any
matches are passed to the specified
closure. The closure is expected to
have the full match in the first
parameter. If there are any capture
groups, they will be placed in
subsequent parameters.

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

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

解决方法:

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

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

可以通过以下方式调用:

"Finds all occurrences of a regular expression string".allIndexOf 's'

并返回(在这种情况下)

[4, 20, 40, 41, 46]

编辑

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

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

然后可以这样调用:

"Finds all occurrences of a regular expression string".allIndexOf( /a[lr]/ )

给:

[6, 32]

编辑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]/ )
}

相关文章

背景:    8月29日,凌晨4点左右,某服务告警,其中一个...
https://support.smartbear.comeadyapi/docs/soapui/steps/g...
有几个选项可用于执行自定义JMeter脚本并扩展基线JMeter功能...
Scala和Java为静态语言,Groovy为动态语言Scala:函数式编程,...
出处:https://www.jianshu.com/p/ce6f8a1f66f4一、一些内部...
在运行groovy的junit方法时,报了这个错误:java.lang.Excep...