15

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.'
}
3
  • 4
    It's not ==~, it's == and ~. At least in Java. Are you talking about Java or Groovy?
    – user253751
    Mar 3, 2015 at 20:17
  • 1
    I'm talking about Groovy, oops.
    – kschmit90
    Mar 3, 2015 at 20:18
  • 3
    When looking at the documentation, can you highlight what is unclear about their difference? groovy-lang.org/operators.html Mar 3, 2015 at 20:22

3 Answers 3

34

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

3
  • 1
    Does ==~ as a match operator apply to variable ==~ 6? Mar 3, 2015 at 20:25
  • 1
    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
    Mar 3, 2015 at 20:34
  • 1
    @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).
    – Marvin
    Jul 20, 2017 at 14:21
10

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
0
6

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.