java escape text in regular expression

Java's built‑in Pattern.quote() method lets you escape arbitrary text so it can be safely used in a regular expression.
For example, if a user enters "$5", you can match that exact string. Without escaping, the dollar sign would be interpreted as an end‑of‑line anchor. Use Pattern.quote() and the method wraps the text in \Q...\E quotes, ensuring every character is taken literally.


Here’s the one-liner :
Pattern.quote("$5");

No comments :

Post a Comment

Your Comment and Question will help to make this blog better...