我不知道目前是否有任何方法,但如果您想要的话,可以将该方法添加到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]/ )
}
String
实例都可用,因此在早期仅调用一次的某个位置是一个不错的选择。为了避免污染String
的元类,您也可以将其作为类别进行处理,但是您需要执行以下操作:use(MyCategory) {"a string".allIndexOf 's'}
。 - tim_yates