regex - unrecognized escape sequence

2019-08-18 10:18发布

问题:

From: https://stackoverflow.com/a/959982/101055

I am trying to use:

using System.Text.RegularExpressions;

Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("goodName1", "asdf");
parameters.Add("goodName2", "qwerty");
string text = "this is my {goodName1} template {goodName2} string";
text = Regex.Replace(text, "\{(.+?)\}", m => parameters[m.Groups[1].Value]);

I get 2 build errors on \{(.+?)\}, on { and } exactly.

ERROR > Unrecognized escape sequence

What is wrong here?

回答1:

try:

text = Regex.Replace(text, @"\{(.+?)\}", m => parameters[m.Groups[1].Value]);

A few more details.

The @ sign defines a Verbatim String Literal. This basically says tells the compiler that the string in quotes is not escaped. http://msdn.microsoft.com/en-us/library/aa691090(v=vs.71).aspx

Optionally, you could have simply doubled up on the back slashes. e.g.:

text = Regex.Replace(text, "\\{(.+?)\\}", m => parameters[m.Groups[1].Value]);

But, IMHO, the @ sign is much more readable.



回答2:

You need to double escape your \ characters so that they're a \ literal within the string, and not used as a string-level escape sequence.

"\\{(.+?)\\}"

Within the string, this has a value of \{(.+?)\}

Alternatively you can use the @"" literal:

@"\{(.+?)\}"

Which has an identical value.


When you need to add a newline to a string, you use an escape sequence, "\n". Strings literals use the \ as an escape character to assist in coding characters that don't exist on a standard keyboard, or are otherwise difficult to place within a string. Regular expressions require using the same \ character to escape special characters in the pattern. This means that the \ character must be escaped to be used as a literal value in the string, which is \\.



回答3:

You can add an @ to escape an entire string, or you can put a double slash, \\ to escape each occurence.

Here is a good article on strings and escaping them from MSDN

An example from the article:

@"c:\Docs\Source\a.txt"  // rather than "c:\\Docs\\Source\\a.txt"