首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从一个字符串中提取所有的电话号码

从一个字符串中提取所有的电话号码
EN

Stack Overflow用户
提问于 2018-08-15 20:36:11
回答 1查看 53关注 0票数 0

我有一个用来识别电话号码的正则表达式。

代码语言:javascript
复制
^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$

我想要做的是从一个字符串中提取所有电话号码,并将其存储在一个数组中。我就是这么做的:

代码语言:javascript
复制
 var rtel = new RegExp(/^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$/gi)

 var r = "Inthe (555)-555-5555 pavithrarox @gmail.com strings below, you 'll find that the content of each 1. abc .  pavithraprbd@gmail.com  line is indented by some whitespace from the index of the line (the number is a part of the text to match). Try writing a pattern that can match each line regardless of how much whitespace is between the number and the content. Notice that the whitespace characters are just like any other character and the special metacharacters like the star and the plus can be used as well.".match(rtel);

但只有当完整字符串仅与正则表达式匹配时,才会匹配。如何从字符串中获取所有电话号码。我错过了什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-08-15 20:41:26

删除正则表达式中的^ (开始)和$ (结束)锚点。如果你把它们放进去,你的整个字符串必须匹配。

代码语言:javascript
复制
var anchors = new RegExp(/^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}$/gi);

var no_anchors = new RegExp(/(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}/gi);

var testString1 = "Inthe (555)-555-5555 pavithrarox @gmail.com strings below, you 'll find that the content of each 1. abc .  pavithraprbd@gmail.com  line is indented by some whitespace from the index of the line (the number is a part of the text to match). Try writing a pattern that can match each line regardless of how much whitespace is between the number and the content. Notice that the whitespace characters are just like any other character and the special metacharacters like the star and the plus can be used as well.";

var testString2 = "(555)-555-5555";

console.log("testString1 - anchors: ", testString1.match(anchors)) // null
console.log("testString1 - no_anchors: ", testString1.match(no_anchors)) // ['(555)-555-5555']

console.log("testString2 - anchors: ", testString2.match(anchors)) // ['(555)-555-5555']
console.log("testString2 - no_anchors: ", testString2.match(no_anchors)) // ['(555)-555-5555']

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51858814

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档