0

I want to replace all escaped quotes, but leave default quotes. How can i do it?

string s1 = '"five1,five2", six ,seven,"eig\"ht1,eight2","nine",,eleven';

String lst = s1.replace('\\"','$');
System.debug(lst);
2
  • 1
    There are unescape methods are present on string class. Use those example - s1.unescapeJava(), s1.unescapeUnicode();
    – Ysr Shk
    Commented Oct 29, 2021 at 10:56
  • @YsrShk it just make them unescaped, but i need to replace them with another symbol.
    – murkofeste
    Commented Oct 29, 2021 at 11:07

1 Answer 1

0

This works:

string s1 = '"five1,five2", six ,seven,"eig\\"ht1,eight2","nine",,eleven';

String lst = s1.replaceAll('\\\\"','\\$');
System.debug(lst);

See e.g. Can't escape the backslash with regex? for some detail on needing multiple levels of escaping.

But the quick explanation is that for a backslash to be treated literally by the Apex compiler it needs to be escaped itself by a backslash, and then another layer of escaping is needed for regex engine too. Hence 2 * 2 = 4 backslashes needed.

And $ has special meaning in regex too, so that character needs escaping.

1
  • Nice, thank you!
    – murkofeste
    Commented Oct 29, 2021 at 11:27

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .