“通用”电话号码的基本正则表达式

时间:2011-06-13 12:27:49

标签: c# asp.net regex validation

我需要一个正则表达式(用于ASP .NET网站)来验证电话号码。它应该是灵活的,唯一的限制是:

  • 应至少为9位
  • 没有字母
  • 可以包括空格,连字符,单个(+)

我搜索了SO和Regexlib.com,但我得到了更多限制的表达,例如英国电话或美国等。

6 个答案:

答案 0 :(得分:18)

^\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

答案 1 :(得分:6)

\+?[\d- ]{9,}

这将匹配数字,可选择以加号开头,然后使用短划线和空格至少包含9个字符。

虽然这意味着破折号和空格会计入九个字符。 我会删除破折号和空格,然后使用

\+?[\d]{9,}

答案 2 :(得分:4)

最好让用户填写他的国家/地区,然后为该国家/地区应用正则表达式。每个国家/地区都有自己的电话号码格式。

答案 3 :(得分:2)

  

^ [0-9- +] + $

<asp:RegularExpressionValidator runat="server" id="rgfvphone" controltovalidate="[control id]" validationexpression="^[0-9-+ ]+$" errormessage="Please enter valid phone!" />

答案 4 :(得分:0)

@"^(?:\+?1[-. ]?)?\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$"

这是我使用的。这将处理大多数情况下的通用电话号码验证。

答案 5 :(得分:0)

这个是超级通用的,只允许给定电话号码中您期望的字符,包括#。它忽略了任何格式模式。

@"^([\(\)\+0-9\s\-\#]+)$"