匹配电话号码的正则表达式 [英] Regular Expression for matching a phone number
问题描述
我需要一个正则表达式来匹配电话号码.我只想知道该号码是否可能是电话号码,并且可以是任何电话格式,美国或国际.所以我制定了一个策略来确定它是否匹配.
I need a regular expression to match phone numbers. I just want to know if the number is probably a phone number and it could be any phone format, US or international. So I developed a strategy to determine if it matches.
我希望它接受以下字符:0-9
以及 ,.()-
并可选择以 +
开头(对于国际号码).如果字符串有任何其他字符,则该字符串不应匹配.
I want it to accept the following characters: 0-9
as well as ,.()-
and optionally start with a +
(for international numbers). The string should not match if it has any other characters.
我试过了:
/\+?[0-9\/\.\(\)\-]/
但它匹配号码中间带有 + 的电话号码.它匹配包含字母字符的数字(我不想要).
But it matches phone numbers that have + in the middle of the number. And it matches numbers that contain alpha chars (I don't want that).
最后,我想将最小长度设置为 9 个字符.
Lastly, I want to set the minimum length to 9 characters.
有什么想法吗?
感谢您的帮助,我显然对 RegEx 的内容不太熟悉 :)
Thanks for any help, I'm obviously not too swift on RegEx stuff :)
推荐答案
嗯,你已经很接近了.试试这个:
Well, you're pretty close. Try this:
^\+?[0-9\/.()-]{9,}$
没有开始和结束锚点,您允许部分匹配,因此它可以匹配字符串 :-)+123
中的 +123
.
Without the start and end anchors you allow partial matching, so it can match +123
from the string :-)+123
.
如果您想要最少 9 个数字,而不是任何字符(因此 ---...///
无效),您可以使用:
If you want a minimum of 9 digits, rather than any characters (so ---...///
isn't valid), you can use:
^\+?[\/.()-]*([0-9][\/.()-]*){9,}$
或者,使用前瞻 - 在匹配 [0-9/.()-]*
的字符串之前,正则表达式引擎正在寻找 (\D*\d){9}
,它是一个 9 位数字,每个数字前面可能有其他字符(我们稍后会验证).
or, using a lookahead - before matching the string for [0-9/.()-]*
the regex engine is looking for (\D*\d){9}
, which is a of 9 digits, each digit possibly preceded by other characters (which we will validate later).
^\+?(?=(\D*\d){9})[0-9\/.()-]*$
这篇关于匹配电话号码的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!