string 如何在 Groovy 中提取子字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25064101/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to extract substring in Groovy?
提问by IAmYourFaja
I have a Groovy method that currently works but is realugly/hacky looking:
我有一个目前有效的 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)
}
When this runs, you might get output like:
运行时,您可能会得到如下输出:
str: wsodk3oke30d30kdl4kof94j93jr94f3kd03k043k?planKey=si23j383&repositoryId=31850514
index: 59
repoIndex: 72
repoId is: 31850514
As you can see, I'm simply interested in obtaining the repositoryId
value (everything after the =
operator) out of the String. Is there a more efficient/Groovier way of doing this or this the only way?
如您所见,我只是对从字符串中获取repositoryId
值(=
运算符之后的所有内容)感兴趣。有没有更有效/更优雅的方式来做这个或这是唯一的方法?
回答by Will
There are a lot of ways to achieve what you want. I'll suggest a simple one using split
:
有很多方法可以实现你想要的。我会建议一个简单的使用split
:
sub = { it.split("repositoryId=")[1] }
str='wsodk3oke30d30kdl4kof94j93jr94f3kd03k043k?planKey=si23j383&repositoryId=31850514'
assert sub(str) == '31850514'
回答by Jeff Storey
Using a regular expression you could do
使用你可以做的正则表达式
def repositoryId = (str =~ "repositoryId=(.*)")[0][1]
The =~
is a regex matcher
这=~
是一个正则表达式匹配器
回答by injecteer
or a shortcut regexp - if you are looking only for single match:
或快捷方式正则表达式 - 如果您只查找单个匹配项:
String repoId = str.replaceFirst( /.*&repositoryId=(\w+).*/, '' )