gpt4 book ai didi

javascript - 从字符串中提取所有电话号码

转载 作者:行者123 更新时间:2023-12-01 01:47:16 24 4
gpt4 key购买 nike

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

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

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

 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);

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

最佳答案

删除正则表达式中的 ^(开始)和 $(结束) anchor 。如果您将它们放入,则整个字符串必须匹配。

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']

关于javascript - 从字符串中提取所有电话号码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51858814/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com