Java 中的 replace() 和 replaceAll() [英] replace() and replaceAll() in Java
问题描述
以下代码使用Java中String
类的replace()
方法.
The following code uses the replace()
method of the String
class in Java.
String a = "abc/xyz";
System.out.println(a.replace("/", "\\"));
给定字符串 a
中的
/
被替换为 \
.
/
in the given String a
is being replaced with \
.
同样的事情是错误的,如果我们使用replaceAll()
方法如下.
The same thing is wrong, if we use the replaceAll()
method as follows.
System.out.println(a.replaceAll("/", "\\"));
它会导致抛出异常 java.lang.StringIndexOutOfBoundsException
.它需要两个额外的反斜杠 \
,如下所示,因为 replaceAll()
使用正则表达式,而 replace()
方法不是这种情况.
It causes the exception java.lang.StringIndexOutOfBoundsException
to be thrown. It requires two additional backslashes \
like the following, since replaceAll()
uses a regex which is not the case with the replace()
method.
System.out.println(a.replaceAll("/", "\\\\"));
唯一的问题是为什么这个方法在只使用两个斜线时会像这样 a.replaceAll("/", "\\")
抛出 java.lang.StringIndexOutOfBoundsException代码>?
The only question is why does this method when used with only two slashes like this a.replaceAll("/", "\\")
throw java.lang.StringIndexOutOfBoundsException
?
另一方面,split()
方法最初发出警告无效的正则表达式:意外的内部错误
(我使用的是 NetBeans 6.9.1).>
The split()
method on the other hand initially issues a waring Invalid regular expression: Unexpected internal error
(I'm using 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
.
An attempt to run this causes the exception java.util.regex.PatternSyntaxException
to be thrown.
因为它使用了像 replaceAll()
这样的正则表达式,所以它需要四个反斜杠.
Since it uses a regex like replaceAll()
, it requires four back slashes.
System.out.println(b.split("\\\\")[0]+b.split("\\\\")[1]);
为什么 a.replaceAll("/", "\\\\");
在前面的例子中没有发出这样的警告或这样的运行时异常,即使它有无效模式?
Why does a.replaceAll("/", "\\\\");
as in the preceding case not issue such a warning or such a run time exception, even though it has an invalid pattern?
推荐答案
来自 Javadoc String.replaceAll
From Javadoc String.replaceAll
请注意,替换字符串中的反斜杠 (\
) 和美元符号 ($) 可能会导致结果与将其视为文字替换字符串时的结果不同;参见 Matcher.replaceAll.如果需要,使用 Matcher.quoteReplacement(java.lang.String) 抑制这些字符的特殊含义.
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 中的 replace() 和 replaceAll()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!