Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused with Groovy regex matching

Tags:

java

regex

groovy

Doing a recent dzone puzzler, matching strings with repeating digits, and I'm confused by the following:

I would expect the following pattern to work: /(\d)\1/

When I use the operator =~ (supposed to create a matcher), this correctly matches

if(!("${num}" =~ /(\d)\1/) )
            println num

Won't print, eg, 77, 100, 222, etc

BUT when I use the ==~ (supposed to evaluate to boolean), ie:

if(!("${num}" ==~ /(\d)\1/) )
            println num

Then it won't print 55, 66, but it WILL print 100, 111. I have to change the pattern to /\d*(\d)\d\d*/ to make it work.

What am I misunderstanding? Why does the pattern work with =~ but not ==~

Any insight appreciated.

like image 765
FOOM Avatar asked Dec 05 '25 05:12

FOOM


1 Answers

=~ creates a matcher
==~ (returns boolean, whether String matches the pattern)

// =~ creates a Matcher, and in a boolean context, it's "true" if it has at least one   
//match, "false" otherwise.
assert "cheesecheese" =~ "cheese"

// ==~ tests, if String matches the pattern
assert "2009" ==~ /\d+/  // returns TRUE

documentation

like image 167
Foo Bar User Avatar answered Dec 06 '25 18:12

Foo Bar User