Convert java string to regex compatible string in replaceAll

Is there a library or any simple way to convert a string and make sure it is compatible as a regular expression to search and replace on another string. Therefore, if the string is "$ money", it is converted to "\ $ money". I tried using StringEscapeUtil.escape, but it does not work with characters like $.

+4
source share
2 answers
+8
source

Prepare \\Q before the line and \\E at the end:

 "\\Q$money\\E" 

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

+5
source

Source: https://habr.com/ru/post/1487381/


All Articles