Question

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

but for

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

output: \s

why do we need extra escape characters in the first case.

Was it helpful?

Solution

  • 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)
  • 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.
  • Your regex is using replacement string of a literal \ followed by a literal s
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top