Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to negate the Groovy Match Operator?

Tags:

regex

groovy

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.

like image 645
TWiStErRob Avatar asked May 06 '15 16:05

TWiStErRob


People also ask

How do I use not equal in groovy?

In groovy, the ==~ operator (aka the "match" operator) is used for regular expression matching. != is just a plain old regular "not equals".

What is ?: In Groovy?

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.

How do you write regex in groovy?

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.

Which of the following is the correct Groovy syntax to match text against a regular expression in Jenkins?

=~ is Groovy syntax to match text against a regular expression.


1 Answers

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?

like image 53
rdmueller Avatar answered Sep 21 '22 17:09

rdmueller