2

Why do I need four backslashes (\) to add one backslash into a String?

String replacedValue = neName.replaceAll(",", "\\\\,");

Here in above code you can check I have to replace all commas (,) from \, but I have to add three more backslash (\) ?

Can anybody explain this concept?

Tunaki
  • 132,869
  • 46
  • 340
  • 423
Subodh Joshi
  • 12,717
  • 29
  • 108
  • 202
  • 2backslashes is not working?? – Sumodh S Sep 15 '15 at 11:16
  • 1
    Use [`replace`](http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#replace-java.lang.CharSequence-java.lang.CharSequence-), not [`replaceAll`](http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#replaceAll-java.lang.String-java.lang.String-) – khelwood Sep 15 '15 at 11:17
  • 4
    see: http://stackoverflow.com/questions/18875852/why-string-replaceall-in-java-requires-4-slashes-in-regex-to-actually-r – rj93 Sep 15 '15 at 11:18

4 Answers4

4

Escape once for Java, and a second time for regexp.

\ -> \\ -> \\\\

Or since you're not actually using regular expressions, take khelwood's advice and use replace(String,String) so you need to only escape once.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
3

The documentation of String.replaceAll(regex, replacement) states:

Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; see Matcher.replaceAll.

The documentation of Matcher.replaceAll(replacement) then states:

backslashes are used to escape literal characters in the replacement string

So to put this more clearly, when you replace with \,, it is as if you were escaping the comma. But what you want is really the \ character, so you should escape it with \\,. Since that in Java, \ also needs to be escaped, the replacement String becomes \\\\,.

If you are having a hard time remembering all this, you can use the method Matcher.quoteReplacement(s), whose goal is to correctly escape the replacement part. Your code would become:

String replacedValue = neName.replaceAll(",", Matcher.quoteReplacement("\\,"));
Tunaki
  • 132,869
  • 46
  • 340
  • 423
1

You have to first escape the backslash because it's a literal (giving \\), and then escape it again because of the regular expression (giving \\\\).

Therefore this -

String replacedValue = neName.replaceAll(",", "\\\\,");  // you need ////

You can use replace instead of replaceAll-

 String replacedValue = neName.replace(",", "\\,"); 
ameyCU
  • 16,489
  • 2
  • 26
  • 41
1

\ is used for escape sequence

For example

  • go to next line then use \n or \r
  • for tab \t
  • likewise to print \ which is special in string literal you have to escape it with another \ which gives us \\

Now replaceAll should be used with a regex, since you're not using a regex, use replace as suggested in the comments.

String s = neName.replace(",", "\\,"); 
benscabbia
  • 17,592
  • 13
  • 51
  • 62