Bali C
Bali C

Reputation: 31231

Escape single and double back slashes

I am trying to replace a string using regex, however I can't seem to find a way to escape the single backslashes for the regex with the double backslashes of the string.

My string literal (this is being read from a text file, as is)

-s \"t\"

and I want to replace it with (again, as a string literal)

-s \"n\"

The best I have been able to come up with is

schedule = Regex.Replace(schedule, "-s\s\\\"\w\\\"", "-s \\\"n\\\"");

The middle argument doesn't compile though, because of the single and double backslashes. It will accept one or the other, but not both (regardless of weather I use @).

I don't use regexes that much so it may be a simple one but I'm pretty stuck!

Thanks

Upvotes: 0

Views: 449

Answers (2)

Tim S.
Tim S.

Reputation: 56536

This works:

var schedule = @"-s \""t\""";
// value is -s \"t\"
schedule = Regex.Replace(schedule, @"-s\s\\""\w\\""", @"-s \""n\""");
// value is -s \"n\"

The escaping is complicated because \ and " have special meanings both in how you encode strings in C# and in regex. The search pattern is (without any escaping) the C# string -s\s\\"\w\\", which tells regex to look for a literal \ and a literal ". The replacement string is -s \"n\", because you don't need to escape the backslashes in a replacement string.

You could, of course, write this with normal strings ("...") instead of verbatim strings (@"..."), but it'd get way messier.

Upvotes: 1

Ibrahim Najjar
Ibrahim Najjar

Reputation: 19423

The problem is happening because \ have a special meaning both for strings and regular expressions so it normally needs to be double escaped unless you use @ and added to the problem here is the presence of " itself inside the string which needs to be escaped.

Try the following:

schedule = Regex.Replace(schedule, @"-s\s\\""\w\\""", @"-s \""n\""");

After using @, \ doesn't have a special meaning inside strings, but it still have a special meaning inside regular expression expression so it needs to be escaped only once if it is needed literally.

Also now you need to use "" to escape " inside the string (how would you escape it otherwise, since \ doesn't have a special meaning anymore).

Upvotes: 2

Related Questions