Escape

String patternStr = "i.e.";

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

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

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

// Returns a pattern where all punctuation characters are escaped.
static Pattern escaper = Pattern.compile("([^a-zA-z0-9])");
public static String escapeRE(String str) {
    return escaper.matcher(str).replaceAll("\\$1");
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.