简体   繁体   English

嵌套量词* C#正则表达式与美国电话号码匹配的例外

[英]Nested quantifier * exception with C# regex matching US phone number

The following expression is supposed to match US phone numbers: 以下表达式应该与美国电话号码匹配:

\(?\d{3}\)?-? *\d{3}-? *-?\d{4}

However, when I use it in my program it thows an error: 但是,当我在程序中使用它时会出现错误:

parsing "(?\\d{3})?-? *\\d{3}-? *-?\\d{4}" - Nested quantifier *. 解析“(?? d {3})?-?* \\ d {3}-?*-?\\ d {4}”-嵌套量词*。

I just can't see where the error is. 我只是看不到错误在哪里。 :( :(

It works well with regex101 for: 它与regex101一起很好地适用于:

(111) 111-1111
111-111-1111
1111111111

but does not seem to work when used with C# Regex. 但与C#正则表达式一起使用时似乎不起作用。

I appreciate any guidance. 我感谢任何指导。 TIA TIA

(C# VS2010 .NET 4.0) (C#VS2010 .NET 4.0)

Edit: This fixes the problem: 编辑:这解决了问题:

 \(?\d{3}\)?-?\s*\d{3}-?\s*-?\d{4}

Still don't know why there was a Nested quantifier error though? 还是不知道为什么为什么会有嵌套量词错误?

The problem with your first regex is that it contains literal spaces that are ignored when using RegexOptions.IgnorePatternWhitespace option. 第一个正则表达式的问题是它包含使用RegexOptions.IgnorePatternWhitespace选项时将被忽略的文字空间。 See this demo , check the Ignore Whitespace option to reproduce the issue. 请参阅此演示检查Ignore Whitespace选项以重现该问题。

Your first regex is thus equal to 因此,您的第一个正则表达式等于

\(?\d{3}\)?-?*\d{3}-?*-?\d{4}
             ^       ^

To make this regex work, do not use the RegexOptions.IgnorePatternWhitespace option, or the * quantifier will be applied to the ? 要使此正则表达式起作用,请不要使用RegexOptions.IgnorePatternWhitespace选项,否则*量词将应用于? quantifier which is not allowed in .NET regex. .NET正则表达式中不允许使用的量词。

Or replace the spaces with [ ] , or \\s . 或用[ ]\\s替换空格。 Eg 例如

\(?\d{3}\)?-?[ ]*\d{3}-?[ ]*-?\d{4}

The space inside a character class is not ignored when using RegexOptions.IgnorePatternWhitespace flag (see RegexOptions Enumeration MSDN page ). 使用RegexOptions.IgnorePatternWhitespace标志时,字符类内部的空间不会被忽略(请参见RegexOptions枚举 MSDN页面 )。

See demo 观看演示

Maybe this? 也许这个吗?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;


namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Regex RegexObj = new Regex("\\(?\\d{3}-?\\)?\\s*\\d{3}-?\\s*-?\\d{4}");
            String Str1 = "(111) 111-1111";
            String Str2 = "111-111-1111";
            String Str3 = "1111111111";
            Console.Write(RegexObj.IsMatch(Str1).ToString() + '\n');
            Console.Write(RegexObj.IsMatch(Str2).ToString() + '\n');
            Console.Write(RegexObj.IsMatch(Str3).ToString() + '\n');


            Console.Read();
        }
    }
}

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM