TWiStErRob
TWiStErRob

Reputation: 46480

How to negate the Groovy Match Operator?

The documentation mentions three regex specific operators:

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.

Upvotes: 37

Views: 26647

Answers (1)

rdmueller
rdmueller

Reputation: 11042

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?

Upvotes: 55

Related Questions