1

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,227
  • 23
  • 133
  • 330

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
  • 761,203
  • 64
  • 569
  • 643
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,451
  • 7
  • 26
  • 43