How can I escape all escape-worthy characters in one line of code?

c#, escaping, regex, string, stringescapeutils

Solution

`Regex.Escape()` only escapes regex reserved characters:

Escapes a minimal set of characters (\, *, +, ?, |, {, [, (,), ^, $,., #, and white space) by replacing them with their escape codes. This instructs the regular expression engine to interpret these characters literally rather than as metacharacters.

Match/Capture a character class of characters you want to escape (note, some characters have special meanings in character classes and need to be escaped like `\` and `-`):

(['^$.|?*+()\\])

And then replace it with a backslash and a reference to the character you want to escape:

\\1

Demo

In C#:

string s = "Woolworth's";
Regex rgx = new Regex("(['^$.|?*+()\\\\])");

string t = rgx.Replace(s, "\\$1");
// Woolworth\'s

Demo

Problem

Based on what I see here (accepted answer), it would seem that I could escape strings by doing this: ``` string s = "Woolworth's"; string t = Regex.Escape(s); MessageBox.Show(t); ``` ...but stepping through that, I see no difference between s and t (I hoped I'd see "Woolworth\'s" as the value of t instead of "Woolworth's" for both vars). I could, I guess, do something like this: ``` string s = "Woolworth's"; s = s.Replace("'", "\'"); ...etc., also escaping the following: [, ^, $, ., |, ?, *, +, (, ), and \ ``` ...but a "one stop shopping" solution would be preferable. To be more specific, I need a string entered by a user to be something that is acceptable as a string value in an Android arrays.xml file. For example, it chokes on this: ``` <item>Woolworth's</item> ``` ...which needs to be this: ``` <item>Woolworth\'s</item> ```

Original source

Related problems