如何找到大字符串中所有出现的子字符串的索引 - (所以基本上是“indexOf”函数的扩展)。有什么想法吗?
现状:
def text = " --- --- bcd -- bcd ---"
def sub = "bcd"
text.indexOf(sub)
// = 9
我想要这样的东西:
def text = " --- --- bcd -- bcd ---"
def sub = "bcd"
text.indexesOf(sub)
// = [9,15]
有这样的功能吗?否则我应该如何实现? (以一种不平凡的方式)
最佳答案
您可以向 String
元类添加新内容,如下所示:
String.metaClass.indexesOf = { match ->
def ret = []
def idx = -1
while( ( idx = delegate.indexOf( match, idx + 1 ) ) > -1 ) {
ret << idx
}
ret
}
def text = " --- --- bcd -- bcd ---"
def sub = "bcd"
text.indexesOf(sub)
据我所知,目前 groovy 中没有任何东西可以让你免费获得这个
关于Groovy:子字符串的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7632942/