开发者

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 开发者_如何学JAVAstr 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.

References

  • JLS 3.10.6 Escape Sequences for Character and String Literals


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.


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:

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

This would print:

Welcome ''thanks'' How are you?


I am confused, do we get different result base on Java version? or do we have not tested answers here?

And here is what did work for me:

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

And this code(which is accepted answer)

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

Only changes first quote.

My java -version:

openjdk version "1.8.0_252"
OpenJDK Runtime Environment (build 1.8.0_252-b09)
OpenJDK 64-Bit Server VM (build 25.252-b09, mixed mode)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜