[英]Nested quantifier * exception with C# regex matching US phone number
以下表達式應該與美國電話號碼匹配:
\(?\d{3}\)?-? *\d{3}-? *-?\d{4}
但是,當我在程序中使用它時會出現錯誤:
解析“(?? d {3})?-?* \\ d {3}-?*-?\\ d {4}”-嵌套量詞*。
我只是看不到錯誤在哪里。 :(
(111) 111-1111
111-111-1111
1111111111
但與C#正則表達式一起使用時似乎不起作用。
我感謝任何指導。 TIA
(C#VS2010 .NET 4.0)
編輯:這解決了問題:
\(?\d{3}\)?-?\s*\d{3}-?\s*-?\d{4}
還是不知道為什么為什么會有嵌套量詞錯誤?
第一個正則表達式的問題是它包含使用RegexOptions.IgnorePatternWhitespace
選項時將被忽略的文字空間。 請參閱此演示 , 檢查 “ Ignore Whitespace
選項以重現該問題。
因此,您的第一個正則表達式等於
\(?\d{3}\)?-?*\d{3}-?*-?\d{4}
^ ^
要使此正則表達式起作用,請不要使用RegexOptions.IgnorePatternWhitespace
選項,否則*
量詞將應用於?
.NET正則表達式中不允許使用的量詞。
或用[ ]
或\\s
替換空格。 例如
\(?\d{3}\)?-?[ ]*\d{3}-?[ ]*-?\d{4}
使用RegexOptions.IgnorePatternWhitespace
標志時,字符類內部的空間不會被忽略(請參見RegexOptions枚舉 MSDN頁面 )。
觀看演示
也許這個嗎?
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.