Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 886
user1053865 Avatar asked Nov 27 '22 09:11

user1053865


2 Answers

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
like image 164
Rob W Avatar answered Nov 30 '22 22:11

Rob W


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}$/
like image 20
ridgerunner Avatar answered Dec 01 '22 00:12

ridgerunner