Escaping Special Characters in a Pattern - Java Regular Expressions

Java examples for Regular Expressions:Pattern

Description

Escaping Special Characters in a Pattern

Demo Code


import java.util.regex.Pattern;

public class Main {
  public void main(String[] argv) {
    String patternStr = "i.e.";
    // Returns a pattern where all punctuation characters are escaped.

    boolean matchFound = Pattern.matches(patternStr, "i.e.");// true
    matchFound = Pattern.matches(patternStr, "ibex"); // true

    // Quote the pattern; i.e. surround with \Q and \E
    matchFound = Pattern.matches("\\Q" + patternStr + "\\E", "i.e."); // true
    matchFound = Pattern.matches("\\Q" + patternStr + "\\E", "ibex"); // false

    // Escape the pattern
    patternStr = escapeRE(patternStr); // i\.e\.

    matchFound = Pattern.matches(patternStr, "i.e."); // true
    matchFound = Pattern.matches(patternStr, "ibex"); // false
  }//from w ww.j a v a  2s  .  c  om

  public static String escapeRE(String str) {
    Pattern escaper = Pattern.compile("([^a-zA-z0-9])");
    return escaper.matcher(str).replaceAll("\\\\$1");
  }
}

Related Tutorials