0

I'm not sure why this regex does not work, what I'm trying to achieve is given the text "user's desktop" I need to convert it to "user\'s desktop".

This is my attempt:

String descrip = "user's desktop";
descrip = descrip.replaceAll("'", "\\'");

But the apostrophe is not replaced. What am I doing wrong?

ps0604
  • 1,513
  • 20
  • 113
  • 274

2 Answers2

4

Your need to escape the backslash twice:

String descrip = "user's desktop";
descrip = descrip.replaceAll("'", "\\\\'");

or better don't use regex:

descrip = descrip.replace("'", "\\'");
//=> user\'s desktop
anubhava
  • 713,503
  • 59
  • 514
  • 593
0

If you want to avoid all the regex overhead, there are some built in methods you can use. Much easier than trying to figure out what to escape or not:

descrip.replaceAll(Pattern.quote("'"), Matcher.quoteReplacement("\\'")
Necreaux
  • 9,052
  • 7
  • 25
  • 43