The line
System.out.println("\\");
prints a single back-slash (\
). And
System.out.println("\\\\");
prints double back-slashes (\\
). Understood!
But why in the following code:
class ReplaceTest { public static void main(String[] args) { String s = "hello.world"; s = s.replaceAll("\\.", "\\\\"); System.out.println(s); } }
is the output:
hello\world
instead of
hello\\world
After all, the replaceAll()
method is replacing a dot (\\.
) with (\\\\
).
Can someone please explain this?
Java String replaceAll() The replaceAll() method replaces each substring that matches the regex of the string with the specified text.
The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement .
Operators: * , + , ? , | Anchors: ^ , $ Others: . , \ In order to use a literal ^ at the start or a literal $ at the end of a regex, the character must be escaped.
When replacing characters using regular expressions, you're allowed to use backreferences, such as \1
to replace a using a grouping within the match.
This, however, means that the backslash is a special character, so if you actually want to use a backslash it needs to be escaped.
Which means it needs to actually be escaped twice when using it in a Java string. (First for the string parser, then for the regex parser.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With