开发者

C# Regex Issue "unrecognized escape sequence"

开发者 https://www.devze.com 2023-03-09 06:18 出处:网络
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 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开发者_C百科}\.){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.


Add an additional '\' to unescape the escape. When it's processed it will then be interpreted in the manner you intended.


The problem is not the regex, but the string. Before compiling it to a regex with the call to IsMatch(), the text you enter is still a normal string and it must obey the language rules.

\d in your language is not a recognized escape sequence, hence the error. You can either double backslashes (\ is the escape sequence to get a ) or, as Blindy pointed out, you can prefix your constant strings with a @, telling the compiler that it should not try to interpret anything looking like an escape sequence to it.

0

精彩评论

暂无评论...
验证码 换一张
取 消