![]() |
The Java Developers Almanac 1.4Order this book from Amazon. |
e428. Escaping Special Characters in a PatternAny nonalphanumeric character can be escaped with a backslash to remove it's special meaning (if any). This example implements a method that escapes all nonalphanumeric characters. This method is useful when the pattern is retrieved programmatically and it is necessary to search for the pattern literally. Another method of escaping the characters in a pattern is to
surround the pattern with 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 // Escape 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"); }
e424. Determining If a String Matches a Pattern Exactly e425. Applying Regular Expressions on the Contents of a File e426. Removing Duplicate Whitespace in a String e427. Greedy and Nongreedy Matching in a Regular Expression
© 2002 Addison-Wesley. |