24

就像是:

def match = "John 19" =~ /(&name&)\w+ (&age&\d+)/
def name = match.name
def age = match.age

是否有一种时髦的语法允许这样的事情(而不是&我虚构的运算符?

4

3 回答 3

41

假设您在 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,则需要第三方正则表达式库

于 2013-03-27T16:59:21.820 回答
20

这不会命名组,但闭包会参数化匹配:

("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/

于 2013-05-16T04:31:08.443 回答
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)'
于 2019-12-04T11:37:36.863 回答