Mega Code Archive

 
Categories / Java Tutorial / Regular Expressions
 

A negative look ahead

import java.util.regex.Matcher; import java.util.regex.Pattern; public class MainClass {   public static void main(String args[]) throws Exception {     // define the pattern     String regex = "First (?!Second)[A-Z]\\w+";     // compile the pattern     Pattern pattern = Pattern.compile(regex);     String candidate = "First Second asdf ";     candidate += "John third, John second asdf, ";     candidate += "John Fourth.";     Matcher matcher = pattern.matcher(candidate);     String tmp = null;     while (matcher.find()) {       tmp = matcher.group();       System.out.println("MATCH:" + tmp);     }   } }