如何使用Groovy的正则表达式获取部分匹配的布尔值? [英] How do I get a Boolean value for a partial match using Groovy's regex?
问题描述
Groovy具有正则表达式匹配运算符"(==~
). 文档表示它返回布尔值,但需要严格匹配".它没有定义严格匹配".
Groovy has a regular expression "match operator" (==~
). The documentation says it returns a Boolean, but requires a "strict match". It does not define "strict match".
我不熟悉此表达式为false
的任何正则表达式系统.但是,这就是Groovy告诉我的.
I'm not familiar with any regex system where this expression is false
. But, that's what Groovy is telling me.
'foo-bar-baz' ==~ /bar/ // => false
find运算符(=~
)返回一个Matcher
,显然可以为匹配和捕获组建立索引.但是,我必须编写一个显式测试才能使该表达式返回布尔值.
The find operator (=~
) returns a Matcher
, which can be indexed for matches and capture groups, apparently. But, I'd have to write an explicit test to have this expression return a Boolean.
('foo-bar-baz' =~ /bar/)[0] != null // => true
两个问题...
- 什么是严格匹配"?
- 如何在不向表达式中添加大量垃圾的情况下获取布尔值?
推荐答案
'foo-bar-baz' ==~ /bar/
等于"foo-bar-baz".matches("bar")
,也就是说,它需要完整的字符串匹配.
The 'foo-bar-baz' ==~ /bar/
is equal to "foo-bar-baz".matches("bar")
, that is, it requires a full string match.
=~
运算符允许 partial 匹配,也就是说,它可以在字符串内找到一个或多个匹配项.
The =~
operator allows partial match, that is, it may find a match/matches inside a string.
因此:
println('foo-bar-baz' ==~ /bar/) // => false
println('bar' ==~ /bar/) // => true
println('foo-bar-baz' =~ /bar/) // => java.util.regex.Matcher[pattern=bar region=0,11 lastmatch=]
参见此 Groovy演示
如果需要检查部分匹配项,则无法避免构建 Matcher
对象:
If you need to check for a partial match, you cannot avoid building a Matcher
object:
使用查找运算符
=~
构建java.util.regex.Matcher
实例
use the find operator
=~
to build ajava.util.regex.Matcher
instance
def text = "some text to match"
def m = text =~ /match/
assert m instanceof Matcher
if (!m) {
throw new RuntimeException("Oops, text not found!")
}
if (!m)
等同于调用if (!m.find())
或者,您可以两次使用!
将结果强制转换为正确的布尔值:
Alternatively, you may use the !
twice to cast the result to correct Boolean value:
println(!!('foo-bar-baz' =~ /bar/))
返回 true .
这篇关于如何使用Groovy的正则表达式获取部分匹配的布尔值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!