就像是:
def match = "John 19" =~ /(&name&)\w+ (&age&\d+)/
def name = match.name
def age = match.age
是否有一种时髦的语法允许这样的事情(而不是&
我虚构的运算符?
假设您在 Java 7+ 上使用,您可以执行以下操作:
def matcher = 'John 19' =~ /(?<name>\w+) (?<age>\d+)/
if( matcher.matches() ) {
println "Matches"
assert matcher.group( 'name' ) == 'John'
assert matcher.group( 'age' ) == '19'
}
else {
println "No Match"
}
如果您还没有使用 java 7,则需要第三方正则表达式库
这不会命名组,但闭包会参数化匹配:
("John 19" =~ /(\w+) (\d+)/).each {match, name, age ->
println match
println name
println age
}
输出:
John 19
John
19
这是一个有用的参考: http: //naleid.com/blog/2008/05/19/dont-fear-the-regexp/
选择:
def foo = '''(id:(1 2 3)) OR (blubb)
(id:(4 5 6)) OR (fasel)
'''
def matcher = (foo =~ /\(id:\((.+)\)\) OR (.*)/)
def (whole, bar, baz) = matcher[0]
assert whole == '(id:(1 2 3)) OR (blubb)'
assert bar == '1 2 3'
assert baz == '(blubb)'
(whole, bar, baz) = matcher[1]
assert whole == '(id:(4 5 6)) OR (fasel)'
assert bar == '4 5 6'
assert baz == '(fasel)'