正则表达式匹配的 Groovy 语法 [英] Groovy syntax for regular expression matching
本文介绍了正则表达式匹配的 Groovy 语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下 Perl 代码的 Groovy 等价物是什么?
What is the Groovy equivalent of the following Perl code?
my $txt = "abc : groovy : def";
if ($txt =~ / : (.+?) : /) {
my $match = $1;
print "MATCH=$match
";
# should print "MATCH=groovy
"
}
我知道有不止一种方法可以做到(包括常规的 Java 方法)——但是什么是Groovy 方法"呢?
I know that there's more than one way to do it (including the regular Java way) - but what is the "Groovy way" of doing it?
这是一种实现方式,但感觉有点笨拙——尤其是数组符号(m[0][1]
),感觉有点奇怪.有没有更好的方法呢?如果不是 - 请描述 m[0][1]
背后的逻辑.
This is one way of doing it, but it feels a bit clumsy - especially the array notation (m[0][1]
) which feels a bit strange. Is there a better way do it? If not - please describe the logic behind m[0][1]
.
def txt = "java : groovy : grails"
if ((m = txt =~ / : (.+?) :/)) {
def match = m[0][1]
println "MATCH=$match"
}
推荐答案
这是我能实现的与 Perl 代码最接近的匹配:
This was the closest match to the Perl code that I could achieve:
def txt = "abc : groovy : def"
if ((m = txt =~ / : (.+?) : /)) {
def match = m.group(1)
println "MATCH=$match"
}
// Prints:
// MATCH=groovy
这篇关于正则表达式匹配的 Groovy 语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文