C#正则表达式“无法识别的转义序列”

我有正在使用的正则表达式的问题,但不知道如何继续使用它们。 我收到错误“无法识别的转义序列”。

我试图列出所有可能有下面代码中列出的格式的电话号码的文件

static void Main(string[] args) { //string pattern1 = "xxx-xxx-xxxx"; //string pattern2 = "xxx.xxx.xxxx"; //string pattern3 = "(xxx) xxx-xxxx"; string[] fileEntries = Directory.GetFiles(@"C:\BTISTestDir"); foreach (string filename in fileEntries) { StreamReader reader = new StreamReader(filename); string content = reader.ReadToEnd(); reader.Close(); string regexPattern1 = "^(\d{3}\.){2}\d{4}$"; string regexPattern2 = "^((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}$"; if(Regex.IsMatch(content, regexPattern1)) Console.WriteLine("File found: " + filename); if(Regex.IsMatch(content, regexPattern2)) Console.WriteLine("File found: " + filename); } Console.WriteLine(Environment.NewLine + "Finished"); Console.ReadLine(); } 

任何帮助深表感谢。

使用@使字符串不再使用转义字符\

  string regexPattern1 = @"^(\d{3}\.){2}\d{4}$"; string regexPattern2 = @"^((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}$"; 

作为旁注,我认为if在两个条件之间使用或( || ),那么你希望最后的两个if是单个。

添加一个额外的’\’来转义逃脱。 当它被处理时,它将以你想要的方式解释。

问题不是正则表达式,而是字符串。 在通过调用IsMatch()将其编译为正则表达式之前,您输入的文本仍然是普通字符串,并且必须遵守语言规则。

你的语言中的\ d不是公认的转义序列,因此错误。 你可以使用双反斜杠(\是获取a的转义序列),或者,正如Blindy所指出的那样,你可以在你的常量字符串前加上@,告诉编译器它不应该尝试解释看起来像转义序列的任何东西。