Separate quotes are replaced by Java

In Java, I have:

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

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

+7
java
source share
4 answers

It looks like you want something like this:

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

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

References

+17
source share

Use

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

You need two levels of escaping in the replacement string: one for Java and one for the regex engine.

+9
source share

This is what worked for me:

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

He prints:

 Welcome \'thanks\' How are you? 
+2
source share

If you come across a question like me, trying to run away for MySQL, you want to add a second single quote to exit:

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

This will print:

 Welcome ''thanks'' How are you? 
0
source share

All Articles