我需要一个正则表达式(用于ASP.NET网站)来验证电话号码。它应该是灵活的,唯一的限制是:
- 至少应为9位数字
- 不得包含字母
- 可以包括空格、连字符和单个“+”
^\s*\+?\s*([0-9][\s-]*){9,}$
分解它:
^ # Start of the string
\s* # Ignore leading whitespace
\+? # An optional plus
\s* # followed by an optional space or multiple spaces
(
[0-9] # A digit
[\s-]* # followed by an optional space or dash or more than one of those
)
{9,} # That appears nine or more times
$ # End of the string
我更喜欢以后一种方式编写正则表达式,因为这样更易于阅读和修改;大多数语言需要设置一个标志,例如C#中的RegexOptions.IgnorePatternWhitespace
。
\+?[\d- ]{9,}
\+?[\d]{9,}
^[0-9-+ ]+$
<asp:RegularExpressionValidator runat="server" id="rgfvphone" controltovalidate="[control id]" validationexpression="^[0-9-+ ]+$" errormessage="Please enter valid phone!" />
这个非常通用,只允许包含在给定电话号码中所期望的字符,包括#。它忽略任何格式模式。
@"^([\(\)\+0-9\s\-\#]+)$"
@"^(?:\+?1[-. ]?)?\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$"
这是我使用的代码。它可以处理大多数情况下的通用电话号码验证。