How does string.replaceAll () work?

I am making a program that replaces a specific part of a string.

String x = "hello";
x=x.replaceAll("e","\\\\s");
System.out.println(x);

output: h \ sllo

but for

System.out.println("\\s");

output: \ s

why do we need extra characters in the first case.

+3
source share
1 answer
  • You need \\for a single character \in regex
  • But the Java string also interprets the backslash, so you need to avoid each \for String, so you need 2 + 2 = 4 backslashes according to one \(2 for String and 2 for the regex engine)
  • , 2- String#replaceAll - , , .
  • \, s
+4

All Articles