正则表达式以匹配具有特定模式的电话号码

时间:2019-05-21 06:35:46

标签: regex regex-negation regex-lookarounds regex-group regex-greedy

我希望能够捕捉到这类电话格式

+xxx xxx xxx xxx
+xxx.xxx.xxx.xxx
+xxx xxxxxxxxx
+xxx-xxx-xxx-xxx
+xxxxxxxxxxxx
xxxx xxx xxx
xxxx xxxxxx
xxxx.xxx.xxx
xxxx-xxx-xxx
xxx-xxx-xxx
xxx.xxx.xxx
xxxxxxxxxx
xxxx xx xx xx
xxxx.xx.xx.xx
xxxx-xx-xx-xx

目前我有此正则表达式

/^[+]?(\d{1,2})?[\s.-]?\(?\d{4}\)?[\s.-]?\d{3}[\s.-]?\d{3}$/

捕获了一些示例,但不知道如何使其也适用于其他格式

1 个答案:

答案 0 :(得分:2)

这些表达式对设计非常敏感,因为我们所有可能的输入都不在列表中。也许更好的选择是只允许数字,或者先删除所有非数字字符,然后再处理/验证它。

但是,如果我们只是希望根据此处列出的输入进行检查,我们也许可以找到一个表达式,也许与此类似:

^[+]?(\d{3,4})[\s.-]?(\d{2,9})?([\s.-])?(\d{2,3})[\s.-]?(\d{2,3})$

DEMO

enter image description here

RegEx

如果不需要此表达式,可以在regex101.com中对其进行修改或更改。

RegEx电路

jex.im还有助于可视化表达式。

enter image description here

JavaScript演示

此代码段只是为了说明捕获组的工作方式:

const regex = /^[+]?(\d{3,4})[\s.-]?(\d{2,9})?([\s.-])?(\d{2,3})[\s.-]?(\d{2,3})$/mg;
const str = `+777 777 777 777
+777.777.777.777
+777 777777777
+777-777-777-777
+777777777777
7777 777 777
7777 777777
7777.777.777
7777-777-777
777-777-777
777.777.777
7777777777
7777 77 77 77
7777.77.77.77
7777-77-77-77`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}