如何使用正则表达式(Regex)从字符串中获取电话号码?

2024-01-05

我想要正则表达式,它通过忽略空格、加号 (+)、括号和破折号来找出连续的最大 12 位数字,例如:

Primary contact number +91 98333332343 call me on this
My number is +91-983 333 32343
2nd number +1 (983) 333 32343, call me
Another one 983-333-32343
One more +91(983)-333-32343 that's all
121 street pin code 421 728 & number is 9833636363

目前,我有一个正则表达式,它负责从字符串中获取联系号码:

/* This only work for the first case not for any other
   and for last one it outputs "121" */

\\+?\\(?\\d*\\)? ?\\(?\\d+\\)?\\d*([\\s./-]?\\d{2,})+

那么这里可以做什么来支持上述所有情况,总之忽略特殊字符,长度应该在10-12之间。


我看到有 10 到 13 位数字。

您可以使用

/(?:[-+() ]*\d){10,13}/g

See the 正则表达式演示 https://regex101.com/r/nZ2dO8/1.

Details:

  • (?:[-+() ]*\d){10,13} - match 10 to 13 sequences of:
    • [-+() ]*- 零个或多个字符-, +, (, ),或一个空格
    • \d- 一个数字
var re = /(?:[-+() ]*\d){10,13}/gm; 
var str = 'Primary contact number +91 98333332343 call me on this\nMy number is +91-983 333 32343\n2nd number +1 (983) 333 32343, call me\nAnother one 983-333-32343\nOne more +91(983)-333-32343 that\'s all\n121 street pin code 421 728 & number is 9833636363';
var res = str.match(re).map(function(s){return s.trim();});
console.log(res);
 
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用正则表达式(Regex)从字符串中获取电话号码? 的相关文章

随机推荐