How to negate the Groovy Match Operator?

19,010

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?

Share:
19,010
TWiStErRob
Author by

TWiStErRob

I'm a principal-level senior software engineer with a masters degree from Hungary working in London, UK. I have experience in multiple fields and technologies: modern web-, mobile- and desktop applications, and their backend services, databases. To name a few: Android, Java, HTML/CSS/JS, WPF.NET, C#, node.js, PHP, SQL, neo4j, C++ in no particular order. I'm a pragmatic perfectionist: efficient, fast, and I pay excessive attention to details when it comes to my work. Check out my homepage for more information about me and my work... All original text, images and source snippets I post on Stack Exchange sites are dedicated to the public domain. Do with them as you see fit. You're also free to apply WTFPL, CC0, Unlicence, or any other similarly permissive licence if necessary.

Updated on June 26, 2022

Comments

  • TWiStErRob
    TWiStErRob almost 2 years

    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.