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".
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
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
Two questions...
The 'foo-bar-baz' ==~ /bar/
is equal to "foo-bar-baz".matches("bar")
, that is, it requires a full string match.
The =~
operator allows partial match, that is, it may find a match/matches inside a string.
Hence:
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=]
See this Groovy demo
If you need to check for a partial match, you cannot avoid building a Matcher
object:
use the find operator
=~
to build ajava.util.regex.Matcher
instancedef text = "some text to match" def m = text =~ /match/ assert m instanceof Matcher if (!m) { throw new RuntimeException("Oops, text not found!") }
if (!m)
is equivalent to callingif (!m.find())
Alternatively, you may use the !
twice to cast the result to correct Boolean value:
println(!!('foo-bar-baz' =~ /bar/))
Returns true.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With