简体   繁体   English

不要将String读为Regex,请按原样阅读

[英]Don't read String as Regex, read AS IS

Basically I am using the following code 基本上我正在使用以下代码

message.replaceFirst(cmd, "");

This is fine HOWEVER sometimes the value of cmd is "\\" and this causes issues as it tries to read this as regex and gives the following error 这很好,但是有时cmd的值为“ \\”,这会导致问题,因为它试图将其读取为正则表达式并给出以下错误

Caused by: java.util.regex.PatternSyntaxException: Unexpected internal error near index 1
\
^
at java.util.regex.Pattern.error(Unknown Source) ~[?:1.7.0_45]
at java.util.regex.Pattern.compile(Unknown Source) ~[?:1.7.0_45]
at java.util.regex.Pattern.<init>(Unknown Source) ~[?:1.7.0_45]
at java.util.regex.Pattern.compile(Unknown Source) ~[?:1.7.0_45]
at java.lang.String.replaceFirst(Unknown Source) ~[?:1.7.0_45]

Basically I want to know if there is a way to get it to read this AS IS without trying to use it as Regex. 基本上,我想知道是否有一种方法可以使它按原样阅读,而不必尝试将其用作正则表达式。

Thanks in advance 提前致谢

You have to use Pattern#quote because \\ is a special character in RegEx. 您必须使用Pattern#quote,因为\\是RegEx中的特殊字符。

message.replaceFirst(Pattern.quote(cmd), "");

You can encounter the same kind of problems in the replacement String as well, in this case use Matcher#quoteReplacement . 您也可能在替换String中遇到相同类型的问题,在这种情况下,请使用Matcher#quoteReplacement

For as is , use: 按原样使用:

String str = Pattern.compile(cmd, Pattern.LITERAL)
                    .matcher(message)
                    .replaceFirst("");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM