admin管理员组

文章数量:1435235

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?

Share Improve this question asked Jan 3, 2016 at 9:49 MalasorteMalasorte 1,1837 gold badges23 silver badges47 bronze badges 2
  • read a regex tutorial. – Casimir et Hippolyte Commented Jan 3, 2016 at 9:50
  • Lazy me gets bad rep :) – Malasorte Commented Jan 3, 2016 at 9:52
Add a ment  | 

4 Answers 4

Reset to default 3
/^(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.

本文标签: javascriptRegexhas six digitsstarts with 01or 2Stack Overflow