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 $.
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.
Java String replaceAll() The replaceAll() method replaces each substring that matches the regex of the string with the specified text.
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.
You can use Pattern.quote("$money")
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With