类似的东西:
def match = "John 19" =~ /(&name&)\w+ (&age&\d+)/
def name = match.name
def age = match.age
是否有一个groovy语法允许这样的东西(而不是我编写的虚构&
运算符?
答案 0 :(得分:34)
假设您使用的是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,则需要third party regex library
答案 1 :(得分:13)
这不会命名组,但是闭包会对匹配进行参数化:
("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/
答案 2 :(得分:0)
替代:
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)'