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
.
In groovy, the ==~ operator (aka the "match" operator) is used for regular expression matching. != is just a plain old regular "not equals".
Yes, the "?:" operator will return the value to the left, if it is not null. Else, return the value to the right. "Yes, the "?:" operator will return the value to the left, if it is not null." - That is incorrect.
A regular expression is a pattern that is used to find substrings in text. Groovy supports regular expressions natively using the ~”regex” expression. The text enclosed within the quotations represent the expression for comparison.
=~ is Groovy syntax to match text against a regular expression.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With