Java: Replace all ' in a string with \'

Iwan Eising picture Iwan Eising · Dec 13, 2013 · Viewed 115.5k times · Source

I need to escape all quotes (') in a string, so it becomes \'

I've tried using replaceAll, but it doesn't do anything. For some reason I can't get the regex to work.

I'm trying with

String s = "You'll be totally awesome, I'm really terrible";
String shouldBecome = "You\'ll be totally awesome, I\'m really terrible";
s = s.replaceAll("'","\\'"); // Doesn't do anything
s = s.replaceAll("\'","\\'"); // Doesn't do anything
s = s.replaceAll("\\'","\\'"); // Doesn't do anything

I'm really stuck here, hope somebody can help me here.

Thanks,

Iwan

Answer

Sage picture Sage · Dec 13, 2013

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

 s.replaceAll("'", "\\\\'");

output:

You\'ll be totally awesome, I\'m really terrible