正则表达式匹配排除0-6数字问题:多位数匹配失效求助
Got it, let's break down what's going wrong here and fix it.
Your current regex ^(?!(0|1|2|3|4|5|6)).* works for single digits 7/8/9 because it checks that the string doesn't start with 0-6. But for multi-digit numbers like 10 or 22, the negative lookahead ^(?!(0|1|2|3|4|5|6)) fails immediately because the first character is 1 or 2 (which are in your excluded list), so the regex doesn't match those multi-digit numbers even though you want them included.
The Correct Regex
What you actually want is to exclude only the single digits 0 through 6, and match everything else (single digits 7-9, plus any multi-digit number). Here's the regex that does that:
^(?:[7-9]|\d{2,})$
Let's Break It Down
^and$: Anchor the regex to the start and end of the string, so we're matching entire numbers (no partial matches).(?:...): A non-capturing group to group our two valid cases together.[7-9]: Matches single digits 7, 8, or 9 (the valid single-digit numbers).|: Acts as an "OR" operator between the two cases.\d{2,}: Matches any sequence of 2 or more digits (covers all multi-digit numbers, regardless of what digits they contain).
Testing It Out
Let's verify with your examples:
2: Doesn't match (it's a single digit 0-6) ✅22: Matches (it's a multi-digit number) ✅7: Matches (single digit 7-9) ✅10: Matches (multi-digit) ✅6: Doesn't match ✅999: Matches ✅
Optional: Exclude Multi-Digit Numbers with Leading Zeros
If you want to avoid matching numbers like 012 (which are technically leading-zero numbers), you can tweak the regex to ensure multi-digit numbers start with a non-zero digit:
^(?:[7-9]|[1-9]\d+)$
This version will reject 012 but still match 10, 22, etc.
内容的提问来源于stack exchange,提问作者Brandon Wilson

