JavaScript 中电话号码的正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15221866/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
RegEx for Phone number in JavaScript
提问by UniqueChar
I was using RegEx to validate user phone numbers. I have set of requirements for phone number validation. I dont have much idea about the RegEX. can anyone help me to provide a matching reqex for my requirement. Here the validation is very simple.
我正在使用 RegEx 来验证用户电话号码。我有一套电话号码验证的要求。我对 RegEX 不太了解。任何人都可以帮助我为我的要求提供匹配的 reqex。这里的验证非常简单。
Conditions
条件
1. It should allow numbers from 0-9.
2. It should allow + sign. (+ sign is not mandatory but not allow after even a single letter (ie: should be placed at front.)).
3. It should allow - sign. (- sign is also not mandatory and can be placed anywhere)
4. It should allow empty space everywhere.
5. No dots or no other chars allowed except the above said things.
Correct values
正确的值
+65-12345678
65-12345678
6512345678
65 12345678
65 123 45678
65 123-45678
+65 123-45678
1234
InCorrect values
不正确的值
12345+86666
123alpha
Thanks
谢谢
回答by Stephan
Based on your samples, try this:
根据您的样本,试试这个:
^(?:\+?\d{2}[ -]?\d{3}[ -]?\d{5}|\d{4})$
It will match allthe correct values.
它将匹配所有正确的值。
DESCRIPTION:
描述:
DEMO:
演示:
回答by Ali Shah Ahmed
Just to help you build some concepts.
The following regex would match the first seven inputs you provided.
只是为了帮助您建立一些概念。
以下正则表达式将匹配您提供的前七个输入。
/^\+?\d{2}[- ]?\d{3}[- ]?\d{5}$/
\+?
would match a +
sign. The ?
in it makes the +
sign optional.\d{2}
matches two digits[- ]?
matches either a -
or a (space).
?
makes the occurrence of -
or (space) optional.
\d{5}
then matches 5 digits.^
and $
are the start and end anchors.
\+?
将匹配一个+
标志。将?
在它使+
标志可选。\d{2}
匹配两位数字[- ]?
匹配 a-
或 a (空格)。
?
使-
或(空格)的出现可选。
\d{5}
然后匹配 5 个数字。^
和$
是开始和结束锚点。
回答by Civa
based on you samples try this pattern.
根据您的样品尝试这种模式。
^(?:\+?\d{2}[ -]?[\d -][\d -]+)$