简体   繁体   中英

extract all the telephone numbers from a string

I have a regex that is written to identify a telephone no.

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

What I want is to do to extract all the telephone numbers from a string and store it in an array. Yhis is what I did:

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

But this only matches if the full string matches the regex only. how do I get all the telephone numbers from the string. what am I missing

Remove the ^ (start) and $ (end) anchors in your regex. If you put these in, your entire string must match.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM