当我这样做的时候
println "line with 1 digit" =~ /\d+/
返回
java.util.regex.Matcher[pattern=\d+ region=0,17 lastmatch=]
但是当我将它转换为 bool 值时 - 它返回 true
或 false
取决于它是否能够在字符串中找到模式
println ((boolean) "line with 1 digit" =~ /\d+/) // true
println ((boolean) "line with no digits" =~ /\d+/) // false
这是否意味着在转换为 boolean
期间它会隐式调用 find
方法?
最佳答案
它叫做“groovy truth”:一组将实例强制转换为 bool 值的规则。
在幕后,Groovy 对该对象调用方法 asBoolean()
。该方法可以在类上实现,也可以通过类别注入(inject)。查看 DefaultGroovyMethods 中的各种“asBoolean”方法或执行 asBoolean(Matcher) :
public static boolean asBoolean(Matcher matcher) {
RegexSupport.setLastMatcher(matcher);
return matcher.find();
}
关于groovy - 转换为 bool 值时,groovy 会隐式调用 Matcher 上的查找吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35529357/