求助编写仅匹配数字1-28的正则表达式(现有表达式失效)
Fixing Your 1-28 Regex Match Issue
Ah, I see the problem with your current regex! The issue comes down to missing start anchors and inconsistent end anchoring, which causes partial matches for numbers like 20-28. Let me break this down and fix it for you.
Why Your Current Regex Fails
Your regex [1-9]|[1][0-9]|[2][0-8]$ has two critical flaws:
- No start anchor (
^): This allows the regex to match any substring within a longer string. For example, when inputting "20", the first alternative[1-9]matches the "2" character, and the regex stops there without checking the rest of the number. - End anchor (
$) only on the last alternative: The$is only applied to the[2][0-8]segment, so even if the regex reached that part, it would only match if "20-28" is the very end of the string—but the lack of a start anchor still lets leading invalid characters slip through.
The Corrected Regex
To ensure we match the entire number (from start to end) and cover all values 1-28, use this regex:
^(?:[1-9]|1[0-9]|2[0-8])$
Let's Break It Down
^: Anchors the match to the start of the string (no leading characters allowed).(?:...): A non-capturing group wrapping our three valid number ranges (we use non-capturing since we don't need to extract individual parts).[1-9]: Matches single-digit numbers from 1 to 9.1[0-9]: Matches two-digit numbers from 10 to 19.2[0-8]: Matches two-digit numbers from 20 to 28.
$: Anchors the match to the end of the string (no trailing characters allowed).
What It Matches
- Single digits: 1, 2, ..., 9
- Two digits: 10, 11, ..., 19, 20, 21, ..., 28
What It Doesn't Match
- 0, 29, 30, or any number outside the 1-28 range
- Strings with extra characters (like "a20" or "20b")
- Empty strings
If you ever need to allow partial matches (though I assume you want exact validation here), you could remove the anchors—but for verifying exact numbers 1-28, the anchored version is the reliable choice.
内容的提问来源于stack exchange,提问作者Kd5490
相关产品推荐
相关产品推荐

