I have following code
String s = "A'BDG";
System.out.println(s.replaceAll("'", "\\'"));
So output is same as String s and it is not replacing ' with \'. However it is working fine with replace(), so whats the problem with replaceAll()?
3 Answers 3
Use
String s = "A'BDG";
System.out.println(s.replaceAll("\\'", "\\\\'"));
You have to escape ' by \\ with replaceAll()
Out put:
A\'BDG
1 Comment
"'", the problem here is with the replacement string.Just use String.replace(CharSequence target, CharSequence replacement) if you are dealing with literal strings:
s.replace("'", "\\'")
It will replace all instances of ' in the string with \'.
The String.replaceAll(String regex, String replacement) and String.replaceFirst(String regex, String replacement) functions works with Pattern (regex).
Though there is no problem with "'" being the pattern, the replacement string "\\'" is the source of your problem. Since the replacement string can contain special sequences such as 1ドル to refer to text captured by capturing group, the syntax must allow plain $ to be specified by escaping \\$. This escaping will cause \' to be interpreted as ' in the replacement string syntax.
This is why you need to double up the escaping "\\\\'" for the replacement string to work correctly. One layer of escaping to give \\' to the replaceAll/replaceFirst function, the next layer to make the replacement string being interpreted as \'.
s.replaceAll("'", "\\\\'")
In such case, Matcher.quoteReplacement(String s) can be used to quote the replacement string when you want to replace with fixed string:
s.replaceAll("'", Matcher.quoteReplacement("\\'"))
Comments
When you are using replace function it identifies the escape symbols differently and add another \\ and call the replaceAll method with correct way. if you do
s.replace("'", "\\'")
it will automatically call
s.replaceAll("\\'", "\\\\'")
But if you call replaceAll function directly It doesn`t have any clue to identify special charactors like ' \ by its own. If you go into replace function you will see that additional \ will be added to this escape characters by quoteReplacement method in replaceall function .
so if you want to use replace all function use it withy extra escape charactors like
s.replaceAll("\\'", "\\\\'")
cheers