What is the difference between ==~ and != in Groovy?

26,875

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:

  1. "1234" ==~ /\d+/ -> evaluates to true
  2. "nonumbers" ==~ /\d+/ -> evaluates to false

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

Share:
26,875
kschmit90
Author by

kschmit90

Updated on March 11, 2020

Comments

  • kschmit90
    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
    Sotirios Delimanolis about 9 years
    Does ==~ as a match operator apply to variable ==~ 6?
  • Marvin
    Marvin about 9 years
    Good question actually. Usually regular expression matching requires slashes, but a short test with 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.
  • Marvin
    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 the 6 as "6" (as the variable is an untyped def).