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

2

7

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 $.

Packaging answered 20/6, 2013 at 22:48 Comment(0)
M
13

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

Matter answered 20/6, 2013 at 22:49 Comment(0)
T
8

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.

Tribunate answered 20/6, 2013 at 22:55 Comment(2)
Thank you! Apparently this is what Pattern.quote() does.Packaging
But what if the String contains \\E in it ?Derry

© 2022 - 2024 — McMap. All rights reserved.