Rein Van Leirsberghe
Rein Van Leirsberghe

Reputation: 765

Regular expression for mobilenumber and phonenumber

Giving the data: 050359554 and 0478770213

I'm searching for a regular expression that will check if the number begins with 04. If it starts with 04, then it should be followed by a 6,7,8 or 9 and 7 digits. Otherwise if it starts with only a 0 and no 4 it should be followed by 8 digits.

My current regex is like

/^(04[6789]\d{7})$|^(0\d{8})$/

The problem with this one is when I enter the number 0478770213 it already says that it's ok at the input of 047877021. But that is not the case.

Upvotes: 1

Views: 55

Answers (3)

anubhava
anubhava

Reputation: 785058

You can use this regex:

^0(?:4[6789]\d{7}|(?!4)\d{8})$

RegEx Demo

Upvotes: 2

Andreas Louv
Andreas Louv

Reputation: 47099

You can use a negative lookahead:

/^(04[6789]\d{7})$|^(0(?!4)\d{8})$/

This will match 0 not followed by 4, followed by 8 digits.

The interesting with a lookahead is that it will not move the search cursor:

0123456789
^ Cursor is here
 ^ Lookahead on this character
^ Cursor is still here

Upvotes: 0

Charly
Charly

Reputation: 282

You have a switch group in the regex you provided, the first one is a 10 digits phone number, the second one is a 9 digits.

In your expectations you said :

Otherwise if it starts with only a 0 and no 4 it should be followed by 8 digits.

But in your regex you did not translate the "and no 4"

Your regex should be :

/^(04[6789]\d{7})$|^(0[0-35-9]\d{7})$/

But something disturbs me, are 9 digits and 10 digits phone number legit? I swear it is a mistake, so i suggest you this :

/^(04[6789]\d{7})$|^(0[0-35-9]\d{8})$/

Upvotes: 0

Related Questions