C#正则表达式问题"无法识别的转义序列" [英] C# Regex Issue "unrecognized escape sequence"

查看:495
本文介绍了C#正则表达式问题"无法识别的转义序列"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an issue with the regular expressions I'm using but don't know how to continue with them. I get the error "unrecognized escape sequence".

我想列出可能有以下

I am trying to list out all files that could have a phone number in the formats listed in the code below

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();
    }



任何帮助深表感谢。

Any help is much appreciated.

推荐答案

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

Use @ to make the strings no longer use the escape character \:

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



作为一个方面说明,我想你想的两个如果■在年底前一个如果的两个条件之间的或( ||

As a side note, I think you want the two ifs at the end to be a single if with an or (||) between the two conditions.

这篇关于C#正则表达式问题"无法识别的转义序列"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆