Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert java string to string compatible with a regex in replaceAll [duplicate]

Is there a library or any easy way to convert a string and make sure its compatible as a regex to look for and replace in another string. So if the string is "$money" it would get converted to "\$money". I tried using StringEscapeUtil.escape but it doesn't work with characters such as $.

like image 607
Kevin Colin Avatar asked Jun 20 '13 22:06

Kevin Colin


People also ask

Does replaceAll use regex?

The method replaceAll() replaces all occurrences of a String in another String matched by regex. This is similar to the replace() function, the only difference is, that in replaceAll() the String to be replaced is a regex while in replace() it is a String.

What is replaceAll \\ s in Java?

Java String replaceAll() The replaceAll() method replaces each substring that matches the regex of the string with the specified text.

What is \\ s+ in regex Java?

The plus sign + is a greedy quantifier, which means one or more times. For example, expression X+ matches one or more X characters. Therefore, the regular expression \s matches a single whitespace character, while \s+ will match one or more whitespace characters.


2 Answers

You can use Pattern.quote("$money").

like image 109
Reimeus Avatar answered Sep 27 '22 20:09

Reimeus


Prepend the \\Q in front of the string, and \\E at the end:

"\\Q$money\\E"

This tells the regex engine that the string between \Q and \E must be interpreted verbatim, ignoring any metacharacters that it may contain.

like image 22
Sergey Kalinichenko Avatar answered Sep 27 '22 20:09

Sergey Kalinichenko