string Phno=txt_EditPhno.Text;
bool check = false;
Regex regexObj = new Regex(@"^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$");
if ((String.IsNullOrEmpty(Phno))||(regexObj.IsMatch(Phno)))
{}
我使用这个正则表达式来允许电话号码,空格,-,(),但它不允许上面提到的任何符号,是我使用的正则表达式是错误的,还是我用错了方法
发布于 2011-11-08 23:36:50
您列出的RegEx字符串工作正常:
System.Text.RegularExpressions.Regex regexObj = new System.Text.RegularExpressions.Regex(@"^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$");
regexObj.IsMatch("(555)-867-5309")
true
regexObj.IsMatch("+15558675309")
true
regexObj.IsMatch("+1.555.867.5309")
true
regexObj.IsMatch("+15558675309ext12345")
true
regexObj.IsMatch("+15558675309x12345")
true
代码中的错误一定在其他地方。你可以使用像RegExLib.com这样的工具来测试你的RegEx。
发布于 2011-11-09 00:42:21
使用稍微不同的方法也可能对您有用...我以前使用过一种方法来获取电话号码信息,包括提取所需的信息并对其重新格式化-您可能有不适合此解决方案的要求,但我还是想建议您这样做。
使用此匹配表达式:
(?i)^\D*1?\D*([2-9])\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d)[^x]*?\s*(?:(?:e?(x)(?:\.|t\.?|tension)?)\D*(\d+))?.*$
和这个替换表达式:
($1$2$3) $4$5$6-$7$8$9$10 $12$13
您应该能够按照指示重新格式化这些输入:
Input Output
----------------------------- --------------------------------
"1323-456-7890 540" "(323) 456-7890 "
"8648217634" "(864) 821-7634 "
"453453453322" "(453) 453-4533 "
"@404-327-4532" "(404) 327-4532 "
"172830923423456" "(728) 309-2342 "
"17283092342x3456" "(728) 309-2342 x3456"
"jh345gjk26k65g3245" "(345) 266-5324 "
"jh3g24235h2g3j5h3x245324" "(324) 235-2353 x245324"
"12345678925x14" "(234) 567-8925 x14"
"+1 (322)485-9321" "(322) 485-9321 "
"804.555.1234" "(804) 555-1234 "
我承认它不是最有效的表达式,但在运行少量文本时,低效的正则表达式通常不是问题,特别是在有知识和细心编写的情况下
要稍微分解一下解析表达式:
(?i)^\D*1?\D* # mode=ignore case; optional "1" in the beginning
([2-9])\D*(\d)\D*(\d)\D* # three digits* with anything in between
(\d)\D*(\d)\D*(\d)\D* # three more digits with anything in between
(\d)\D*(\d)\D*(\d)\D*(\d)[^x]*? # four more digits with anything in between
\s* # optional whitespace
(?:(?:e?(x)(?:\.|t\.?|tension)?) # extension indicator (see below)
\D*(\d+))? # optional anything before a series of digits
.*$ # and anything else to the end of the string"
这三个数字不能以0或1开头。分机指示符可以是x
、ex
、xt
、ext
(都可以以句点结尾)、extension
或xtension
(不能以句点结尾)。
如前所述,分机(即数字)必须是一系列连续的数字(但正如给定表达式所假设的那样,它们通常是连续的)
我们的想法是使用正则表达式引擎提取前10位数字(不包括"0“和"1",因为美国国内电话号码不是以这些数字开头的(除了作为开关,它不是必需的,也不总是需要的,并且不依赖于目标电话,而是您正在键入的电话。然后,它将尝试取出任何'x',并捕获'x',以及其后的第一个连续的数字字符串。
它允许相当大的容忍度来格式化输入,同时去除有害的数据或元字符,然后产生格式一致的电话号码(这在许多层面上经常得到认可)
https://stackoverflow.com/questions/8049932
复制相似问题