Javascript RegExp - 从字符串中提取电话号码 [英] Javascript RegExp - extract phone numbers from string
问题描述
我有以下工作正则表达式以提取不同格式的大量电话号码。
I have the following working regex to extract a lot of phone numbers in different formats.
请参阅此处: http://jsfiddle.net/SB5Ly/4/
var regex = new RegExp(
"\\+?\\(?\\d*\\)? ?\\(?\\d+\\)?\\d*([\\s./-]?\\d{2,})+",
"g"
);
....
(如果脚本未加载,请按运行 顶部菜单中的按钮
(If the script didn't load, press the "Run" button from the top menu)
正如您在示例中看到的(通过链接),最后2-3个电话号码格式(var phoneNumbers)没有t匹配使用的正则表达式。
你可以测试正则表达式在脚本中修改它并运行它。
As you can see in the example (by following the link), the last 2-3 phone number formats (var phoneNumbers) doesn't match the used regex. You can test the regex modifying it in the script and running it.
所以我需要一个匹配所有枚举电话号码格式的正则表达式(提取它们)来自整个网页(document.body.innerHTML))。
So i need a regex that match all the enumerated phone number formats (to extract them from an entire webpage (document.body.innerHTML)).
推荐答案
我不知道你想要的规定性如何,但是这符合你的所有例子:
I don't know how prescriptive you want to be, but this matches all your examples:
var regex = new RegExp("\\+?\\(?\\d*\\)? ?\\(?\\d+\\)?\\d*([\\s./-]?\\d{2,})+", "g");
查看现场演示。
正则表达式的一个小错误:想要的时候要在字符类中包含文字短划线,要么将其转义,要么将其放在第一位或最后一位。
One small bug with your regex: When wanting to include a literal dash in a character class, either escape it or place it first or last.
你有 [\\s- 。]
,这是不正确的。它应该是 [\\\\ .-]
, [ - \\\\。]
或 [\\\\\\ - 。]
。
You had [\\s-.]
, which is incorrect. It should be either [\\s.-]
, [-\\s.]
or [\\s\\-.]
.
这篇关于Javascript RegExp - 从字符串中提取电话号码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!