regex - unrecognized escape sequence

不问归期 提交于 2019-12-13 05:31: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"


来源:https://stackoverflow.com/questions/10318665/regex-unrecognized-escape-sequence

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!