Using negation in Regular expressions - Java Regular Expressions

Java examples for Regular Expressions:Pattern

Introduction

negation starts the class with a caret

The following pattern says that he string must be a three-letter word that ends in at, but isn't fat or cat.

Demo Code

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

public class Main {
  public static void main(String[] args) {
    Pattern pattern = Pattern.compile("[^cf]at");
    Matcher matcher = pattern.matcher("bat");
    if (matcher.matches())
      System.out.println("Match.");
    else/*from   w w w  . ja  v a2 s .  c  o  m*/
      System.out.println("Does not match.");
  }

}

Related Tutorials