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

12,909

Solution 1

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

Solution 2

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}$/
Share:
12,909
user1053865
Author by

user1053865

Updated on June 05, 2022

Comments

  • user1053865
    user1053865 almost 2 years

    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.

  • Roger Lindsjö
    Roger Lindsjö over 12 years
    An explanation of the parts in the regex would make the answer evenbetter. Especially when using non capturing groups and greedy quantifiers other than ? and * as those are exotic feature to most developers.
  • Wiseguy
    Wiseguy over 12 years
    I would've just done /^(01|02|08)\d{8,9}$/, but this works too and could be more flexible later.
  • Rob W
    Rob W over 12 years
    @Wiseguy I saw: "10 or 11 digits long, starting with ...". For this reason, I decided to suplly a pattern which can easily be re-used and extended (what if the following criteria is added: or starts with 112) ;)
  • user1053865
    user1053865 over 12 years
    Thanks that worked great am i right in say if i have/^(?=\d{10,11}$)(01|02|08|03|07)\d+/ it will mean it allows 03 and 07 as well ? if so that's great massive help thank you
  • Rob W
    Rob W over 12 years
    @user1053865 Yes, that works as well. If the prefixes are of a fixed size, you can also use the following pattern (although, for an unexperienced user, its effect is not as obvious as the previous pattern): ^0[12378]\d{8,9}$ (= START 0 one of 12378 8 or 9 digits END).
  • ridgerunner
    ridgerunner over 12 years
    Why would someone downvote this answer? It is simple, fast and accurate. Go figure...
  • Davyd Geyl
    Davyd Geyl almost 4 years
    Great answer. Helped me to see other ways to construct regex for this task.