0

I am facing issues when using not contains in regx

 some text good foo and some text and good koo 
 good foo and some text (no indication of koo)

I like to filter all good foo records but no koo. In this case only 2nd record. I tried to use

.* good foo.*((?!(good koo)).)* .*

But it is flagging all the records having the word good foo

/* no indication of good koo, so expected is true) */
println("good foo and some text (no indication of koo)".matches(".*good foo.*((?!(good koo)).)* .*"))  

/* indication of good koo, so expected is false) */
println("good foo and some text good koo".matches(".*good foo.*((?!(good koo)).)* .*"))
Pshemo
  • 122,468
  • 25
  • 185
  • 269
John
  • 1,531
  • 6
  • 18
  • 30
  • Sorry, but I am not able to fully understand what you are trying to achieve. Can you provide some example of expected result along with logic which lead you to that result? – Pshemo Dec 25 '18 at 13:15
  • Also if you have some code and you believe it should work, post it because problem may not be in regex but how you are using it. – Pshemo Dec 25 '18 at 13:16
  • sorry, I just added some samples, hope that will help – John Dec 25 '18 at 13:28
  • You may use [`string.matches("(?!.*\\bgood koo\\b).*\\bgood foo\\b.*");`](https://regex101.com/r/HbWRwa/2) – anubhava Dec 25 '18 at 13:38

1 Answers1

1

If you are trying to do this match line by line, then the following pattern should work:

^(?=.*\bgood foo\b)(?!.*\bgood koo\b).*$

Demo

This uses positive and negative lookaheads to assert that good foo does appear somewhere in the line, and that good koo does not appear in that same line. Then, it accepts anything else to appear in that line.

Note that I put word boundaries \b around good foo and good koo to ensure that, for example, the pattern does not give a false flag match to good food.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360