0

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

3 Answers 3

1

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}/.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Let me understand the conditions.
They are accepting 8xxxxxxxx types but not 9xxxxxxxxx ones.
0
var numberPattern = /([+]91)?9[0-9]{9}\b/;

1 Comment

@AbhishekDey try removing the first \b..+ is breaking the boundary..Check out the edit
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.