How to escape text for regular expression in Java

Viewed 233133

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.

8 Answers

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"));

I think what you're after is \Q$5\E. Also see Pattern.quote(s) introduced in Java5.

See Pattern javadoc for details.

^(Negation) symbol is used to match something that is not in the character group.

This is the link to Regular Expressions

Here is the image info about negation:

Info about negation

Related