[英]How does string.replaceAll() work?
I am making a program that replaces a certain part of the string. 我正在制作一个替换字符串某个部分的程序。
String x = "hello";
x=x.replaceAll("e","\\\\s");
System.out.println(x);
output: h\\sllo 输出: h \\ sllo
but for 但对于
System.out.println("\\s");
output: \\s 输出: \\ s
why do we need extra escape characters in the first case. 为什么我们在第一种情况下需要额外的转义字符。
\\\\
for a single \\
character in regex \\
字符需要\\\\
\\
for String hence you need 2+2=4 backslashes to match a single \\
(2 for String and 2 for regex engine) \\
转义字符串,因此你需要2 + 2 = 4个反斜杠来匹配单个\\
(2个用于字符串,2个用于正则表达式引擎) String#replaceAll
method is also interpreted by regex engine due to potential presence of back-references and that is the reason same regex rules apply for replacement string also. String#replaceAll
方法的第二个参数也由正则表达式引擎解释,因为可能存在反向引用,这也是同样的正则表达式规则同样适用于替换字符串的原因。 \\
followed by a literal s
\\
替换字符串,后跟文字s
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.