Tutorial :Single quotes replace in Java



Question:

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.


Solution:1

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.

References


Solution:2

Use

"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.


Solution:3

This is what worked for me:

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

It prints:

Welcome \'thanks\' How are you?  


Solution:4

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:

str.replaceAll("\\'","\\'\\'")  

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
Previous
Next Post »