Tutorial :Single quotes replace in Java


In Java I have:

String str = "Welcome 'thanks' How are you?";  

I need to replace the single quotes in str by \', that is, when I print str I should get output as Welcome \'thanks\' How are you.


It looks like perhaps you want something like this:

    String s = "Hello 'thanks' bye";      s = s.replace("'", "\\'");      System.out.println(s);      // Hello \'thanks\' bye  

This uses String.replace(CharSequence, CharSequence) method to do string replacement. Remember that \ is an escape character for Java string literals; that is, "\\'" contains 2 characters, a backslash and a single quote.




"Welcome 'thanks' How are you?".replaceAll("'", "\\\\'")  

You need two levels of escaping in the replacement string, one for Java, and one for the regular expression engine.


This is what worked for me:

"Welcome 'thanks' How are you?".replaceAll("\\'", "\\\\'");  

It prints:

Welcome \'thanks\' How are you?  


In case you come to this question like me with trying to escape for MySQL, you want to add a second single quote to escape:


This would print:

Welcome ''thanks'' How are you?  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »