Reputation: 1639
I'm extracting the phone numbers that begin with 9 followed by other 9 digits from tweets using JavaScript.
Here's the regex pattern I am using:
var numberPattern = /^9[0-9]{9}/;
Here's the pattern matching phase:
var numberstring = JSON.stringify(data[i].text);
if(numberPattern.test(data[i].text.toString()) == true){
var obj={
tweet : {
status : data[i].text
},
phone : numberstring.match(numberPattern)
}
//console.log(numberstring.match(numberPattern));
stringarray.push(obj);
The problem is it is working for few numbers and not all. Also, I want to modify the regex to accept +91 prefix to numbers as well and(or) reject a starting 0 in numbers. I'm a beginner in regex, so help is needed. Thanks.
Example:
#Chennai O-ve blood for @arun_scribbles 's friend's father surgery in few days. Pl call 9445866298. 15May. via @arun_scribbles
Upvotes: 0
Views: 51
Reputation: 92
Try this regex pattern: [\+]?[0-9]{1,4}[\s]?[0-9]{10}
It accepts any country code with +
, a space
, and then 10 digit number.
Upvotes: 0
Reputation: 3558
Your regex pattern seems to be designed to allow a 9 or 8 at the beginning, but it would be better to enclose that choice in parentheses: /^(9|8)[0-9]{9}/
.
To allow an optional "+" at the beginning, follow it with a question mark to make it optional: /^\+?(9|8)[0-9]{9}/
.
To allow any character except "0", replace the (9|8)
with a construct to accept only 1-9: /^\+?[1-9][0-9]{9}/
.
And in your example, the phone number doesn't come at the beginning of the line, so the caret will not find it. If you're looking for content in the middle of the line, you'll need to drop the caret: /\+?[1-9][0-9]{9}/
.
Upvotes: 1