user1053865
user1053865

Reputation: 89

Need a regex that makes sure the number starts with 01 02 or 08 and is 10 or 11 digits long

Am having hard time crediting a regex to check if a number starts with 01, 02 or 08 and is ten or eleven digits long.

For example I want numbers formatted like this to pass:

01614125745
02074125475
0845895412
08004569321

and numbers other forms to fail, number like:

0798224141
441544122444
0925456754

and so on. Basically, any number that does not start with 01 02 or 08.

Upvotes: 4

Views: 16141

Answers (2)

ridgerunner
ridgerunner

Reputation: 34385

Rob W's answer is correct. But I'd use a simpler expression like this: (No need for lookahead)

/^0[128][0-9]{8,9}$/

Upvotes: 12

Rob W
Rob W

Reputation: 348982

The following pattern follows the criteria:

/^(?=\d{10,11}$)(01|02|08)\d+/   # This pattern can easily be extended

/^(?=\d{10,11}$)0[128]\d{8,9}/   # Same effect

Explanation:

^                Begin of string
(?=\d{10,11}$)   Followed by 10 or 11 digits, followed by the end of the string
(01|02|08)       01, 02 or 08
\d+              The remaining digits

Upvotes: 20

Related Questions