What is the difference between ==~ and != in Groovy?
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
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
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 /
.