Groovy has a regular expression \"match operator\" (==~
). The documentation says it returns a Boolean, but requires a \"strict match\". It does not define \"str
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.