简体   繁体   中英

Unable to replace escape character through String.replaceAll in java

I am trying a replace a \\ using String.replaceAll and i get an Exception while doing so. Here is my code:

    String str = "1^\\";
    System.out.println("\nInitial string length: "+str.length()+ " Initial String is:     "+str);
    String temp = str.replaceAll("[&@;^\\]","");

This is the output:

Initial string length: 3 Initial String is: 1^\

Exception in thread "main" java.util.regex.PatternSyntaxException: Unclosed character     class near index 6
 [&@;^\]
  ^
at java.util.regex.Pattern.error(Pattern.java:1713)
at java.util.regex.Pattern.clazz(Pattern.java:2254)
at java.util.regex.Pattern.sequence(Pattern.java:1818)
at java.util.regex.Pattern.expr(Pattern.java:1752)
at java.util.regex.Pattern.compile(Pattern.java:1460)
at java.util.regex.Pattern.<init>(Pattern.java:1133)
at java.util.regex.Pattern.compile(Pattern.java:823)
at java.lang.String.replaceAll(String.java:2190)

The \\\\ escaping is being swallowed by the string literal, so the string you're parsing as a regex is actually [&@;^\\] .

\\] in a regex escapes the ] , so you have an unclosed character class.

You need to double-escape the \\ ; once for the string literal and once for the regex.

The escape character for String and regex are the same. This means to get

\\\\ - in the String
\\ - in the regex
\ - means

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