Does Java have a built-in way to escape arbitrary text so that it can be included in a regular expression? For example, if my users enter "$5", I'd like to match that exactly rather than a "5" after the end of input.
+27
A:
Yes:
http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/Pattern.html#quote(java.lang.String)
Pattern.quote("$5");
Mike Stone
2008-09-12 23:39:52
Other's have posted equally viable options, so really pick the one that makes the code prettiest to you! :-)
Mike Stone
2008-09-12 23:51:09
+1
A:
I think what you're after is \Q$5\E. Also see Pattern.quote(s) introduced in J5.
See Pattern javadoc for details.
Rob Oxspring
2008-09-12 23:42:16
I'm curious if there's any difference between this and using the LITERAL flag, since the javadoc says there is no embedded flag to switch LITERAL on and off: http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/Pattern.html#LITERAL
Chris Mazzola
2009-08-06 20:51:42
+5
A:
Difference between Pattern.quote and Matcher.quoteReplacement was not clear to me before I saw following example
s.replaceFirst(Pattern.quote("text to replace"),
Matcher.quoteReplacement("replacement text"));
Pavel Feldman
2008-09-12 23:52:14