35

The documentation mentions three regex specific operators:

  • ~ returning a Pattern
  • =~ returing a Matcher
  • ==~ returning a boolean

Now, how can I negate the last one? (I agree that the others can't have any meaningful negation.)

I tried the obvious thinking:

println 'ab' ==~ /^a.*/ // true: yay, matches, let's change the input
println 'bb' ==~ /^a.*/ // false: of course it doesn't match, let's negate the operator
println 'bb' !=~ /^a.*/ // true: yay, doesn't match, let change the input again
println 'ab' !=~ /^a.*/ // true: ... ???

I guess the last two should be interpreted like this rather:

println 'abc' != ~/^b.*/

where I can see new String("abc") != new Pattern("^b.*") being true.

TWiStErRob
  • 44,762
  • 26
  • 170
  • 254
  • 2
    it's about an operator that does this and `!(...)` is no option? – cfrick May 06 '15 at 16:07
  • I don't know if there is a "not match" operator, but you can always negate the result like this: `println !('abc' ==~ /^a.*/)` – Casimir et Hippolyte May 06 '15 at 16:09
  • It would be nice if there was a concise way, but if not, that's an obvious answer :( I just expected more I guess, like Perl has `!~`. – TWiStErRob May 06 '15 at 16:13
  • 2
    fell into the same trap (if such it be). But "!=~" shouldn't be able to be interpreted as "equivalent" to "!= ~" ! ... white space is usually one of the main factors in syntax parsing in just about every computer language! IMHO it should throw a compile/scripting error. – mike rodent Feb 07 '18 at 20:25

1 Answers1

53

AFAIK, there is no negated regular expression match operator in Groovy.

So - as already mentioned by cfrick - it seems that the best answer is to negate the whole expression:

println !('bb' ==~ /^a.*/)

Another solution is to invert the regular expression, but it seems to me to be less readable:

How can I invert a regular expression in JavaScript?

Community
  • 1
  • 1
rdmueller
  • 10,742
  • 10
  • 69
  • 126