Groovy:子字符串的索引?

标签 groovy

如何找到大字符串中所有出现的子字符串的索引 - (所以基本上是“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/

相关文章:

json - Grails/Groovy数字分隔符在调用$ .getJSON时丢失

sql - hibernate 4.3.6 QuerySyntaxException : Path expected for join

gradle - 任务是否复制了同一项目中另一个任务的所有依赖项?

unit-testing - 在 Grails 应用程序中,我应该将 Groovy 类的测试用例放在哪里?

gradle - Jacoco Gradle 中的最小代码覆盖阈值

java - 使用 this 关键字作为 Jenkins 文件中类构造函数的参数

datetime - Groovy 持续时间

grails - Grails/groovy项目的静态代码分析

java - Groovy 文字正则表达式/\\/未编译

json - 将 json 或 json 数组绑定(bind)到 grails 对象