Reputation: 1086
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 . [email protected] 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
Upvotes: 0
Views: 74
Reputation: 1167
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 . [email protected] 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']
Upvotes: 2