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);
 
if(m.matches()){
	System.out.println("Match!");
}else{
	System.out.println("No");
}

1. Look Ahead

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

.*program(?=creek).*

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.

.*(?<=program)creek.*

programcreek matches
softwarecreek doesn’t match

Leave a Comment