下面的代码使用了Java中String
类的replace()
方法。
String a = "abc/xyz";
System.out.println(a.replace("/", "\\"));
给定字符串 a
中的 /
将替换为 \
。
如果我们使用 replaceAll()
方法,同样是错误的。
System.out.println(a.replaceAll("/", "\\"));
它会引发异常 java.lang.StringIndexOutOfBoundsException
。它需要两个额外的反斜杠 \
,如下所示,因为 replaceAll()
使用正则表达式,而 replace()
方法不是这种情况。
System.out.println(a.replaceAll("/", "\\\\"));
唯一的问题是为什么这个方法在只使用两个斜杠时会像这样 a.replaceAll("/", "\\")
抛出 java.lang.StringIndexOutOfBoundsException
?
另一方面,split()
方法最初发出警告 无效的正则表达式:意外的内部错误
(我使用的是 NetBeans 6.9.1)。
String b="abc\\xyz";
System.out.println(b.split("\\")[0]+b.split("\\")[1]); //Issues a warning as specified.
尝试运行它会导致抛出异常 java.util.regex.PatternSyntaxException
。
因为它使用像 replaceAll()
这样的正则表达式,所以它需要四个反斜杠。
System.out.println(b.split("\\\\")[0]+b.split("\\\\")[1]);
为什么 a.replaceAll("/", "\\\\");
不会发出这样的警告或这样的运行时异常,即使它有一个模式无效?
最佳答案
来自 Javadoc String.replaceAll
Note that backslashes (
\
) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; see Matcher.replaceAll. Use Matcher.quoteReplacement(java.lang.String) to suppress the special meaning of these characters, if desired.
System.out.println(a.replaceAll("/", Matcher.quoteReplacement("\\")));
关于java - Java 中的 replace() 和 replaceAll(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12941266/