views:

7676

answers:

3

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
Other's have posted equally viable options, so really pick the one that makes the code prettiest to you! :-)
Mike Stone
+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
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
+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