Java regex to escape apostrophe -


this question has answer here:

i'm not sure why regex not work, i'm trying achieve given text "user's desktop" need convert "user\'s desktop".

this attempt:

string descrip = "user's desktop"; descrip = descrip.replaceall("'", "\\'"); 

but apostrophe not replaced. doing wrong?

your need escape backslash twice:

string descrip = "user's desktop"; descrip = descrip.replaceall("'", "\\\\'"); 

or better don't use regex:

descrip = descrip.replace("'", "\\'"); //=> user\'s desktop 

Comments