请求生成验证5位数字前两位符合指定范围的正则表达式
Absolutely! This validation rule can be fully implemented with a regular expression. Let’s break this down clearly so you can understand every part, even if you’re new to regex.
First, let’s align your rules to regex logic
Your requirements translate to:
- The input must be 1 to 5 digits (since you specified "最多包含5位数字" — maximum 5 digits)
- If the input has 2 or more digits, the first two must fall into one of these ranges:
00-16,20-25,32-39
The Regular Expression (covers 1-5 digit inputs)
Here’s the regex that handles all valid cases:
^(?:(0[0-9]|1[0-6]|2[0-5]|3[2-9])\d{0,3}|\d)$
Let’s unpack each part
Let’s break down what every segment does so you know exactly what you’re using:
^: Ensures we start matching from the very first character of the input (no extra characters before the digits)(?:...): A non-capturing group (groups our valid two-digit options without storing the match for later use)0[0-9]: Matches any two-digit number from00to091[0-6]: Matches any two-digit number from10to162[0-5]: Matches any two-digit number from20to253[2-9]: Matches any two-digit number from32to39|: Acts like an "OR" — the regex will accept any of the preceding valid two-digit patterns
\d{0,3}: Matches 0 to 3 additional digits (combining with the two-digit prefix gives us valid lengths from 2 to 5 digits)|\d: An extra "OR" to match single-digit inputs (since a single digit has no "first two digits" to validate)$: Ensures we match all the way to the end of the input (no extra characters after the digits)
If you only need to validate exact 5-digit inputs
Looking at your examples, all valid/invalid test cases are 5-digit numbers. If your actual requirement is exactly 5 digits (not up to 5), use this simplified regex instead:
^(0[0-9]|1[0-6]|2[0-5]|3[2-9])\d{3}$
This works because:
- We match the valid first two digits, then exactly 3 more digits (
\d{3}) to make a total of 5 - The
^and$anchors guarantee there are no extra characters before or after the 5 digits
Testing with your samples
Let’s confirm against your provided examples:
- Valid 5-digit inputs:
00789,11569,22698,32567→ all match the regex - Invalid 5-digit inputs:
17895(first two digits17are outside allowed ranges),41578(first two digits41are outside allowed ranges) → neither matches the regex
Quick code usage note
Since you’re using regex.IsMatch, you can drop this string directly into your regex library. For example (in C#):
string validationRegex = @"^(0[0-9]|1[0-6]|2[0-5]|3[2-9])\d{3}$"; // For exact 5-digit validation bool isValid = Regex.IsMatch(yourInputNumber, validationRegex);
(Use the first regex string if you need to support 1-5 digit inputs.)
内容的提问来源于stack exchange,提问作者Nerdherder Ed

