How to define a regex that matches two different lines, but not the third

I am new to the regex concept in Java. how to define a regular expression that matches the phrase “money”, “more money”, but not the phrase “no money”?

+4
source share
3 answers

That would be something like this

(more )?money

If you need more words:

(more |less )?money

+3
source

To match all lines containing "money" without "no", use a negative lookbehind:

 (?<!no )money 

Here are some examples. Note that I added .* Before and after the regular expression anywhere in the line:

 re = ".*(?<!no )money.*" "blah blah blah money blah blah blah".matches(re) => true "blah blah blah more money blah blah blah".matches(re) => true "blah blah blah no money blah blah blah".matches(re) => false 
+1
source

You can do this with regular expressions ... and I think that "(?<!no)( more)? money" should do the trick for your example.

But this is not a very good way to parse text:

  • It can give false positives; eg

     "domino money" -- matches 

    and false negatives; eg.

     "more money" -- doesn't match because we didn't allow for multiple spaces. 
  • As the language you test becomes richer, you get a combinatorial explosion in your regular expressions. This makes it difficult to read / maintain your regular expressions and can lead to performance problems.

+1
source

Source: https://habr.com/ru/post/1486198/


All Articles