Regex: Contains a word, doesn't contain another word
java, regex
Solution
I'm just going to refine your first approach (`( method )(?!.*efficient.*)`).
You already said `Almost there`, so why not take this approach a bit further? I just added a word-boundary `\b` before `efficient`, so it won't exclude `unefficient`:
^.+(method)(?!.*\befficient.*)
demo @ regex101
Now there's one thing left:
this is an efficient method
would still be an unwanted match (I suppose).
So you can add the look-ahead in front of your main-group to get rid of this match.
^(?!.*\befficient.*).*(method)
demo @ regex101
In order to match `efficient` exactly you should add another word-boundary, otherwise it will match on `efficients`, too:
^(?!.*\befficient\b).*(\bmethod)
If you want to make `method` an exact match, too, just add another boundary after it. For now this would match on `methods`.
Problem
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.