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.'
}
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.
def var = 3;
resulted in: var ==~ 4;
being false
and var ==~ 3;
being true
, so there might be some kind of special handling. I'm no groovy expert though.
/foo/
is in fact the same as "foo"
. And I believe that groovy simply treats the 6
as "6"
(as the variable is an untyped def
).
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 to true
"nonumbers" ==~ /\d+/
-> evaluates to false
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 /
.
==~
, it's==
and~
. At least in Java. Are you talking about Java or Groovy?