我希望在Groovy中匹配正则表达式,检查返回了多少个组,然后使用其中一个组,但是得到:
java.lang.IllegalStateException: No match found
如果我打电话 match.groupCount() match.group(1)
match.groupCount()
match.group(1)
def match = "Some text" =~ /(text)/ if (match.groupCount() >= 1) { print match.group() // error } // or def match = "Some text" =~ /(text)/ if (match) { print match.group() // success }
你的第一个变体在调用前 groupCount() find() 或 matches()
groupCount()
find()
matches()
def match = "Some text" =~ /(text)/ if (match.find()) { println match.groupCount() print match.group() // error }
这个 if (match) {...} asBoolean() 那就是电话 查找() 在火柴上
if (match) {...}
asBoolean()
查找()
还有一些更简单的变体
("Some text 2 text" =~ /text/).each{ println it }
或
println (("Some text 2 text" =~ /text/).collect())