Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String's replaceAll() method and escape characters

Tags:

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?

like image 538
Surender Thakran Avatar asked Jun 02 '12 20:06

Surender Thakran


People also ask

What is replaceAll \\ s in Java?

Java String replaceAll() The replaceAll() method replaces each substring that matches the regex of the string with the specified text.

What do the replaceAll () do?

The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement .

What characters should be escaped in regex?

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.


1 Answers

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.)

like image 194
Reverend Gonzo Avatar answered Oct 13 '22 00:10

Reverend Gonzo