简体   繁体   中英

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

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.

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 .

For as is , use:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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