如何编写正则表达式匹配指定开头范围的8位数字?
Regex to Match 8-Digit Numbers with Specific Starting Ranges
Got it, let's break this down step by step to build the right regex for your requirement. Here's the final pattern you can use:
^((2[0-9]|3[01])|4[0-2]|5[0-3]|6[0-1]|71|81|9[1-3])\d{6}$
Let's break down each part:
^and$: These are anchors that ensure we're matching the entire string as an 8-digit number (if you need to match these numbers within a larger text, replace them with word boundaries\binstead, like\b((2[0-9]|3[01])|4[0-2]|5[0-3]|6[0-1]|71|81|9[1-3])\d{6}\b).- The grouped starting pairs cover all your required ranges:
2[0-9]|3[01]: Handles 20-31 —2[0-9]matches 20-29, and3[01]covers 30-31.4[0-2]: Directly matches 40, 41, 42.5[0-3]: Matches 50 through 53.6[0-1]: Covers 60 and 61.71&81: Exact matches for these two starting pairs.9[1-3]: Matches 91, 92, 93.
\d{6}: Matches any 6 digits after the starting pair, bringing the total length to exactly 8 digits.
Test Examples:
Valid matches:
- 20123456 (starts with 20)
- 31987654 (starts with 31)
- 42000000 (starts with 42)
- 53111111 (starts with 53)
- 61222222 (starts with 61)
- 71333333 (starts with 71)
- 81444444 (starts with 81)
- 93555555 (starts with 93)
Invalid matches:
- 19123456 (starts with 19, outside range)
- 32987654 (starts with 32, exceeds 31)
- 43000000 (starts with 43, exceeds 42)
- 70111111 (starts with 70, not in allowed list)
- 90222222 (starts with 90, outside range)
- 1234567 (only 7 digits)
- 123456789 (9 digits, too long)
内容的提问来源于stack exchange,提问作者Therese
相关产品推荐
相关产品推荐

