Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a Boolean value for a partial match using Groovy's regex?

Tags:

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".

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...

  1. What is a "strict match"?
  2. How do I get a Boolean value without adding a ton of garbage to my expression?
like image 837
Anthony Mastrean Avatar asked Jul 19 '17 15:07

Anthony Mastrean


1 Answers

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 a java.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) is equivalent to calling if (!m.find())

Alternatively, you may use the ! twice to cast the result to correct Boolean value:

println(!!('foo-bar-baz' =~ /bar/))

Returns true.

like image 83
Wiktor Stribiżew Avatar answered Oct 01 '22 04:10

Wiktor Stribiżew