简体   繁体   English

正则表达我们的电话号码

[英]regular expression us phone number

I have a regular expression that matches the following numbers. 我有一个与以下数字匹配的正则表达式。

8702431273 8702431273

973-882-9444 ext 6114 973-882-9444转6114

1-223-332-2232 1-223-332-2232

However it does not match. 但它不匹配。

(+1) 623-975-5296 (+1)623-975-5296

605-367-7321 605-367-7321

How can I modify this to also accept these. 如何修改它以接受这些。

^(?:1(?:[. -])?)?(?:\((?=\d{3}\)))?([2-9]\d{2})(?:(?<=\(\d{3})\))? ?(?:(?<=\d{3})[.-])?([2-9]\d{2})[. -]?(\d{4})(?: (?i:ext)\.? ?(\d{1,5}))?$

It looks to me like you can simply replace this part at the beginning: 在我看来,你可以在开头简单地替换这部分:

^(?:1(?:[. -])?)?

with this: 有了这个:

^(?:\(?\+?1\)?(?:[. -])?)?

Or if you want to be strict about the parentheses matching: 或者,如果您想严格匹配括号:

^(?:(?:\((?=.?1\)))?\+?1\)?(?:[. -])?)?

I would incorporate next part to your regexp to match those other telephones: 我会将下一部分合并到你的正则表达式以匹配其他电话:

(?:\(\+\d\)\s)

It means the plus sign with a digit. 它表示带数字的加号。 Adapt it if can be more digits inside parenthesis or more space after it. 如果括号内可以有更多数字或者后面有更多空格,请调整它。 Final regexp could be like this. 最终的正则表达式可能是这样的。

^(?:(?:1(?:[. -])?)?(?:\((?=\d{3}\)))?|(?:\(\+\d\)\s))?([2-9]\d{2})(?:^(?<=\(\d{3})\))? ?(?:(?<=\d{3})[.-])?([2-9]\d{2})[. -]?(\d{4})(?: (?i:ext)\.? ?(\d{1,5}))?$

I divide in lines the part I've changed to adapt new telephone numbers: 我将我改变的部分划分为适应新的电话号码:

^
  (?:
    (?:1(?:[. -])?)?
    (?:\((?=\d{3}\)))?
      |
    (?:\(\+\d\)\s)
   )?
([2-9]\d{2})(?:^(?<=\(\d{3})\))? ?(?:(?<=\d{3})[.-])?([2-9]\d{2})[. -]?(\d{4})(?: (?i:ext)\.? ?(\d{1,5}))?$

In my test it works with the five telephones of your post. 在我的测试中,它适用于您帖子的五部电话。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM