I need a regex that will match a number containing six digits. The first digit must be 0, 1, or 2.
For example - 054654 or 198098 or 265876.
So far I got this: /^\d{6}$/
- matches a number containing six digits. How do I add the second requirement: first digit must be 0, 1, or 2?
I need a regex that will match a number containing six digits. The first digit must be 0, 1, or 2.
For example - 054654 or 198098 or 265876.
So far I got this: /^\d{6}$/
- matches a number containing six digits. How do I add the second requirement: first digit must be 0, 1, or 2?
/^(0|1|2)\d{5}$/
That one should work
You can just use a character class:
/^[012]\d{5}$/
This tells the regex engine to match only one out of several characters, in this case 0
, 1
or 2
. To create a character class, place the characters you want to match between square brackets.
So the regex that you have written /^\d{6}$/ only matches 6 digits that start and end. You have to add (0|1|2) in the start where | means or and the final is /^(0|1|2)\d{5}$/ or /^[012]\d{5}$/.
This should do what you want:
/^(0|1|2)[0-9]{5}$/
|
means or
.