Mega Code Archive

 
Categories / Java / Regular Expressions
 

Escaping Special Characters in a Pattern

import java.util.regex.Pattern; public class Main {   public static void main(String[] argv) throws Exception {     String patternStr = "i.e.";     boolean matchFound = Pattern.matches(patternStr, "i.e.");     matchFound = Pattern.matches(patternStr, "ibex");      // Quote the pattern; i.e. surround with \Q and \E     matchFound = Pattern.matches("\\Q" + patternStr + "\\E", "i.e.");      matchFound = Pattern.matches("\\Q" + patternStr + "\\E", "ibex");      // Escape the pattern     patternStr = escapeRE(patternStr);     matchFound = Pattern.matches(patternStr, "i.e.");      matchFound = Pattern.matches(patternStr, "ibex");      // Returns a pattern where all punctuation characters are escaped.   }   public static String escapeRE(String str) {     Pattern escaper = Pattern.compile("([^a-zA-z0-9])");     return escaper.matcher(str).replaceAll("\\\\$1");   } }