【问题标题】:How to extract substring in Groovy?如何在 Groovy 中提取子字符串?
【发布时间】:2014-09-23 16:55:23
【问题描述】:

我有一个 Groovy 方法,目前有效,但 真实 丑陋/骇人听闻:

def parseId(String str) {
    System.out.println("str: " + str)
    int index = href.indexOf("repositoryId")
    System.out.println("index: " + index)
    int repoIndex = index + 13
    System.out.println("repoIndex" + repoIndex)
    String repoId = href.substring(repoIndex)
    System.out.println("repoId is: " + repoId)
}

运行时,您可能会得到如下输出:

str: wsodk3oke30d30kdl4kof94j93jr94f3kd03k043k?planKey=si23j383&repositoryId=31850514
index: 59
repoIndex: 72
repoId is: 31850514

如您所见,我只是对从字符串中获取repositoryId 值(= 运算符之后的所有内容)感兴趣。有没有更有效/更规范的方式来做到这一点或这是唯一的方式?

【问题讨论】:

  • 使用正则表达式捕获您要查找的模式

标签: string syntax groovy substring


【解决方案1】:

有很多方法可以实现您想要的。我会建议一个简单的使用split

sub = { it.split("repositoryId=")[1] }

str='wsodk3oke30d30kdl4kof94j93jr94f3kd03k043k?planKey=si23j383&repositoryId=31850514'

assert sub(str) == '31850514'

【讨论】:

  • 我得到一个错误:类没有这样的属性子:org.gradle.api.internal.project.DefaultProject_Decorated
  • @IgorGanapolsky 你是从脚本运行它吗?尝试在sub 前面添加def
  • @Will,我如何只得到下一个数字而不是后面的数字?您的解决方案是在关键字之后返回所有内容。例如我有字符串,“当前检索任务的请求 ID:09Sg00000052eIJEAY [sf:retrieve] 等待服务器完成处理请求......”。我试图只得到“09Sg00000052eIJEAY”。我知道我必须修改索引。但到目前为止我想不通
  • 知道了!!! def sub = { it.split("当前检索任务:")[1][0..18] } .... 赞成答案:)
【解决方案2】:

使用正则表达式可以做到

def repositoryId = (str =~ "repositoryId=(.*)")[0][1]

=~ 是一个正则表达式匹配器

【讨论】:

  • = 不见了 :)
【解决方案3】:

或快捷方式正则表达式 - 如果您只寻找单个匹配项:

String repoId = str.replaceFirst( /.*&repositoryId=(\w+).*/, '$1' )

【讨论】:

    猜你喜欢
    • 2011-11-17
    • 1970-01-01
    • 2013-07-06
    • 2010-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多