简体   繁体   English

string.replaceAll()如何工作?

[英]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. 为什么我们在第一种情况下需要额外的转义字符。

  • You need \\\\ for a single \\ character in regex 正则表达式中的单个\\字符需要\\\\
  • But Java string also interprets backslash therefore you need to escape each \\ for String hence you need 2+2=4 backslashes to match a single \\ (2 for String and 2 for regex engine) 但是Java字符串也会解释反斜杠,因此你需要为每个\\转义字符串,因此你需要2 + 2 = 4个反斜杠来匹配单个\\ (2个用于字符串,2个用于正则表达式引擎)
  • Also note that 2nd argument to 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方法的第二个参数也由正则表达式引擎解释,因为可能存在反向引用,这也是同样的正则表达式规则同样适用于替换字符串的原因。
  • Your regex is using replacement string of a literal \\ followed by a literal s 你的正则表达式是使用文字\\替换字符串,后跟文字s

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

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