Groovy正则表达式命名捕获组必须调用match方法吗?

时间:2019-01-15 06:33:43

标签: regex groovy

我试图在Groovy中使用名为捕获组的正则表达式。 this question中的示例代码有效:

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"
}

但是如果我删除if语句,如下所示:

def matcher = 'John 19' =~ /(?<name>\w+) (?<age>\d+)/
println "Matches"
assert matcher.group( 'name' ) == 'John'
assert matcher.group( 'age' ) == '19'

Groovy抱怨:

Matches
Caught: java.lang.IllegalStateException: No match found
java.lang.IllegalStateException: No match found
    at java_util_regex_Matcher$group.call(Unknown Source)
    at test.run(test.groovy:3)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

那是为什么?我认为matches()仅返回给定的字符串是否与正则表达式匹配?

我正在使用Groovy版本:2.5.4 JVM:11.0.1供应商:Oracle Corporation操作系统:Mac OS X

谢谢!

0 个答案:

没有答案