Regular Expression: exclude a word/string

If you want to exclude a certain word/string in a search pattern, a good way to do this is regular expression assertion function. It is indispensable if you want to match something not followed by something else.

A Simple Example

String str = "programcreek";
Pattern p = Pattern.compile(".*program(?=creek).*");
Matcher m = p.matcher(str);

1. Look Ahead

In the example above, if you want to find "programcreek", but not "programriver". You can use the pattern:


programcreek matches
programriver doesn't match

?= is positive lookahead and ?! is negative lookahead.

2. Look Behind

Lookbehind is similar. We can use ?<= for positive look behind and ?<! for negative lookbehind.


programcreek matches
softwarecreek doesn't match

Category >> Regular Expressions  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
String foo = "bar";