What is the difference between ==~ and != in Groovy?
Solution 1
In groovy, the ==~
operator (aka the "match" operator) is used for regular expression matching. !=
is just a plain old regular "not equals". So these are very different.
cf. http://groovy-lang.org/operators.html
Solution 2
In Java, !=
is “not equal to” and ~
is "bitwise NOT". You would actually be doing variable == ~6
.
In Groovy, the ==~
operator is "Regex match". Examples would be:
-
"1234" ==~ /\d+/
-> evaluates totrue
-
"nonumbers" ==~ /\d+/
-> evaluates tofalse
Solution 3
In Groovy you also have to be aware that in addition to ==~
, alias "Match operator", there is also =~
, alias "Find Operator" and ~
, alias "Pattern operator".
All are explained here.
==~
result type: Boolean
/boolean
(there are no primitives in Groovy, all is not what it seems!)
=~
result type: java.util.regex.Matcher
~
result type: java.util.regex.Pattern
I presume the Groovy interpreter/compiler can distinguish between ~
used as a Pattern operator and ~
used as a bitwise NOT (i.e. its use in Java) through context: the former will always be followed by a pattern, which will always be bracketed in delimiters, usually /
.
kschmit90
Updated on March 11, 2020Comments
-
kschmit90 about 4 years
What is the difference between these?
Why use one over the other?
def variable = 5 if( variable ==~ 6 && variable != 6 ) { return '==~ and != are not the same.' } else { return '==~ and != are the same.' }
-
Sotirios Delimanolis about 9 yearsDoes
==~
as a match operator apply tovariable ==~ 6
? -
Marvin about 9 yearsGood question actually. Usually regular expression matching requires slashes, but a short test with
def var = 3;
resulted in:var ==~ 4;
beingfalse
andvar ==~ 3;
beingtrue
, so there might be some kind of special handling. I'm no groovy expert though. -
Marvin almost 7 years@SotiriosDelimanolis To finally shed some more light on this question: The slashes in groovy are not a special requirement for patterns but instead just another way of declaring a string. So
/foo/
is in fact the same as"foo"
. And I believe that groovy simply treats the6
as"6"
(as the variable is an untypeddef
).