我正在开发一个表达式来验证所有可能的电话号码格式。我有 50%,它没有通过 * 验证我接受的字符。 - 空格
这是规则
It can contain open and close parenthesis ex. (55)
It can contin or not '+' char ex. (+52)
It can contain 2 or 3 numbers inside parenthesis ex. (+555) o (+55)
It can contain whitespace between close parenthesis and the next numbers ex. (55) 44332211
The consecutive numbers to the parenthesis must be 6 or 8 numbers ex. (55)443322 o (55)44332211
The consecutive numbers to the parenthesis can contain whitespaces, dashes, asterisks, or colons. ex.(55)44-33-22-11 o (55)44 33 22 11 o (55)44*33*22*11 o (55)44.33.22.11
The consecutive numbers to the parenthesis can be divided in groups of 2, 3 or 4 numbers ex. (55)5544-3322 o (55)55 44 33 22 o (555)444*333
The number format can come in a row of 8, 10 o 12 numbers ex. 55443322 o 5544332211 o 554433221100
这是正则表达式
[\(]?[\+]?(\d{2}|\d{3})[\)]?[\s]?((\d{6}|\d{8})|(\d{3}[\*\.\-\s]){3}|(\d{2}[\*\.\-\s]){4}|(\d{4}[\*\.\-\s]){2})|\d{8}|\d{10}|\d{12}
我做错了什么?我留下了一个示例脚本,我正在为 Python 做的正则表达式,我不知道我是否用 JS 改变了很多
$(function(){
$('ul li').each(function(){
let number = $(this).text();
let regex = /^[\(]?[\+]?(\d{2}|\d{3})[\)]?[\s]?((\d{6}|\d{8})|(\d{3}[\*\.\-\s]){3}|(\d{2}[\*\.\-\s]){4}|(\d{4}[\*\.\-\s]){2})|\d{8}|\d{10}|\d{12}$/;
let res = regex.test( number );
$(this).text( $(this).text() + ' is: ' + res);
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Telephone numbers
<ul>
<li>test</li>
<li>(55)test</li>
<li>(55)333-test</li>
<li>(55)test 22</li>
<li>554433221100</li>
<li>5544332211</li>
<li>55443322</li>
<li>(55)443322</li>
<li>(55)44332211</li>
<li>(+55)443322</li>
<li>(+55)44332211</li>
<li>(55)4433*2211</li>
<li>(55)444.333</li>
<li>(55)44-33-22-11</li>
<li>(55)4433-2211</li>
<li>(+55)443 322</li>
</ul>
请您参考如下方法:
你可以使用
^(?:\d{8}(?:\d{2}(?:\d{2})?)?|\(\+?\d{2,3}\)\s?(?:\d{4}[\s*.-]?\d{4}|\d{3}[\s*.-]?\d{3}|\d{2}([\s*.-]?)\d{2}\1\d{2}(?:\1\d{2})?))$
参见 regex demo .
详情
^- 字符串的开始(?:- 外部分组构造的开始:\d{8}- 8 位数字(?:\d{2}(?:\d{2})?)?- 可选的 2 位数字,后跟可选的 2 位数字子字符串(例如 8、10 或可匹配12位字符串)
|- 或者\(- 一个(\+?- 1 或 0 个加号\d{2,3}- 2 或 3 位数字\)- 一个)字符\s?- 1 或 0 个空格(?:- 一个分组:\d{4}- 4 位数字[\s*.-]?- 一个空格,*,.或-,一个可选出现\d{4}- 4 位数字
|- 或\d{3}[\s*.-]?\d{3}- 3 位数字,一个定界字符,3 位数字
|- 或者\d{2}([\s*.-]?)\d{2}\1\d{2}(?:\1\d{2})?: 2 位数字,第 1 组捕获的分隔符字符,2 位数字,与第 1 组中相同的分隔符,2 位数字,以及与第 1 组中相同的分隔符字符和两位数的可选序列
)- 内部分组结束。
)- 外分组结束$- 字符串结尾。
