最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - Regex - has six digits, starts with 0, 1, or 2 - Stack Overflow

matteradmin6PV0评论

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.

Post a comment

comment list (0)

  1. No comments so far