How to escape text for regular expression in Java

Matt picture Matt · Sep 13, 2008 · Viewed 220.3k times · Source

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.

Answer

Mike Stone picture Mike Stone · Sep 13, 2008

Since Java 1.5, yes:

Pattern.quote("$5");