Negative Look ahead : Lookup « Regular Expressions « Java

Negative Look ahead

Negative Look ahead

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class NegativeLookaheadExample {
  public static void main(String args[]) throws Exception {
    String regex = "John (?!Smith)[A-Z]\\w+";
    Pattern pattern = Pattern.compile(regex);

    String candidate = "I think that John Smith ";
    candidate += "is a fictional character. His real name ";
    candidate += "might be John Jackson, John Westling, ";
    candidate += "or John Holmes for all we know.";

    Matcher matcher = pattern.matcher(candidate);

    String tmp = null;

    while (matcher.find()) {
      tmp =;
      System.out.println("MATCH:" + tmp);


Related examples in the same category

1.Positive Look behind 1Positive Look behind 1
2.Positive Look aheadPositive Look ahead
3.Positive Look Behind 2Positive Look Behind 2
4.Positive Look Behind 3Positive Look Behind 3
5.Regular Expression: find
6.Java Regular Expression : find 2
7.Java Regular Expression : File and Find