Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex: Contains a word, doesn't contain another word

Tags:

java

regex

I'm unsuccessfully trying to find a solution to this problem: To find a Java regex that can recognize a String containing one word and not containing another word.

To be more clear, as an example, let's check if my sentence to contains "method" and do not contains "efficient" as whole words (meaning it has not to be part of another word). The regex matcher should return, e.g.,:

This method was efficient.      false   (contains "method", but contains "efficient")
This method was unefficient.    true    (cont. "method" doesn't cont. "efficient")
This method was simple.         true    (cont. "method" doesn't cont. "efficient")
This routine is efficient       false   (cont. "efficient" but no "method")

What I've tried so far, at least the more nearest solution results.

( method )(?!.*efficient.*)      Almost there, but "unefficient" also triggers.
( method )(?!.* efficient .*)    No. Now " method " doesn't trigger anymore.
((.*method.*)(?!.*efficient.*))  No. the absence of "efficient" doesn't trigger.

So it seems to be a problem of exact word match. So I also tried at first:

 (.*\bmethod\b.*)(?!.*efficient.*)

Also to not to depend on spaces to bound each word. But nothing. I tried almost the whole day and it's painful.

I am using http://www.regular-expressions.info/refquick.html as a reference website, and http://regexpal.com/ for testing.

Thank you! D.

like image 466
donnadulcinea Avatar asked Feb 18 '14 08:02

donnadulcinea


1 Answers

How about:

^(?=.*\bmethod\b)(?!.*\befficient\b)
like image 102
Toto Avatar answered Oct 25 '22 13:10

Toto