微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐