简体   繁体   English

无法通过Java中的String.replaceAll替换转义字符

[英]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. 我正在尝试使用String.replaceAll替换\\ ,并且这样做时出现异常。 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. String和regex的转义字符相同。 This means to get 这意味着要

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

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

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