关于电话号码的正则表达式模式的普遍抱怨是,它们需要将真正可选的字符作为破折号和其他项目。
为什么它们不能是可选的并且有模式不在乎它们是否存在?
以下模式为用户提供了可选的破折号、句点和括号,并使用命名捕获将重点放在数字上。
模式被注释(使用# 并跨越多行)所以使用正则表达式选项IgnorePatternWhitespace 除非删除 cmets。因为该标志不影响正则表达式处理,它只允许通过 # 字符和换行符对模式进行注释。
string pattern = @"
^ # From Beginning of line
(?:\(?) # Match but don't capture optional (
(?<AreaCode>\d{3}) # 3 digit area code
(?:[\).\s]?) # Optional ) or . or space
(?<Prefix>\d{3}) # Prefix
(?:[-\.\s]?) # optional - or . or space
(?<Suffix>\d{4}) # Suffix
(?!\d) # Fail if eleventh number found";
上述模式只查找 10 个数字并忽略任何填充字符,例如 ( 或破折号 - 或空格或制表符,甚至是 .。例子是
(555)555-5555 (OK)
5555555555 (ok)
555 555 5555(ok)
555.555.5555 (ok)
55555555556 (not ok - match failure - too many digits)
123.456.789 (failure)
同一模式的不同变体
没有cmets的模式不再需要使用IgnorePatternWhiteSpace:
^(?:\(?)(?<AreaCode>\d{3})(?:[\).\s]?)(?<Prefix>\d{3})(?:[-\.\s]?)(?<Suffix>\d{4})(?!\d)
不使用命名捕获时的模式
^(?:\(?)(\d{3})(?:[\).\s]?)(\d{3})(?:[-\.\s]?)(\d{4})(?!\d)
使用ExplicitCapture 选项时的模式
^\(?(?<AreaCode>\d{3})[\).\s]?(?<Prefix>\d{3})[-\.\s](?<Suffix>\d{4})(?!\d)