Single quotes replace in Java

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.

Tags:

Java