正则表达式 - 简单的电话号码 [英] Regex - simple phone number

查看:66
本文介绍了正则表达式 - 简单的电话号码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有很多关于如何匹配某些电话号码类型的正则表达式示例.对于我的示例,我只想允许数字和一些特殊字符.我再次无法实现这一点.

I know there are a ton of regex examples on how to match certain phone number types. For my example I just want to allow numbers and a few special characters. I am again having trouble achieving this.

应该允许的电话号码可以采用这些形式

Phone numbers that should be allowed could take these forms

5555555555
555-555-5555
(555)5555555
(555)-555-5555
(555)555-5555 and so on

我只想要一些允许 [0-9] 以及特殊字符 '(' , ')' 和 '-' 的东西

I just want something that will allow [0-9] and also special characters '(' , ')', and '-'

到目前为止我的表情是这样的

so far my expression looks like this

/^[0-9]*^[()-]*$/

我知道这是错误的,但从逻辑上讲,我相信这意味着允许数字 0-9 或并允许字符 (, ) 和 -.

I know this is wrong but logically I believe this means allow numbers 0-9 or and allow characters (, ), and -.

推荐答案

^(\(\d{3}\)|\d{3})-?\d{3}-?\d{4}$

  • \(\d{3}\)|\d{3} 带或不带 () 的三位数字 - 更简单的正则表达式是 \(?\d{3}\)? 但这将允许 (555-5555555555)5555555
  • 一个可选的 - 后跟三位数字
  • 一个可选的 - 后跟四位数字
    • \(\d{3}\)|\d{3} three digits with or without () - The simpler regex would be \(?\d{3}\)? but that would allow (555-5555555 and 555)5555555 etc.
    • An optional - followed by three digits
    • An optional - followed by four digits
    • 请注意,这仍然允许 555555-5555555-5555555 - 我不知道这些是否包含在您的等中 部分

      Note that this would still allow 555555-5555 and 555-5555555 - I don't know if these are covered in your and so on part

      这篇关于正则表达式 - 简单的电话号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆