java 将java字符串转换为与replaceAll中的正则表达式兼容的字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17225107/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert java string to string compatible with a regex in replaceAll
提问by Kevin Colin
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 $.
是否有库或任何简单的方法来转换字符串并确保它与正则表达式兼容以在另一个字符串中查找和替换。因此,如果字符串是“$money”,它将被转换为“\$money”。我尝试使用 StringEscapeUtil.escape 但它不适用于诸如 $ 之类的字符。
回答by Reimeus
You can use Pattern.quote("$money")
.
您可以使用Pattern.quote("$money")
.
回答by dasblinkenlight
Prepend the \\Q
in front of the string, and \\E
at the end:
预先考虑\\Q
在前面的字符串,并\\E
在最后:
"\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.
这告诉正则表达式引擎必须逐字解释\Q
和之间的字符串\E
,忽略它可能包含的任何元字符。