正则表达式优化:限制手机号格式并禁止10位重复数字
Fixing the Regex to Block All-Same-Number Phone Numbers
Let's break down why your original attempt didn't work, then build the correct regex that meets your requirements.
The Problem with Your Current Approach
Your negated lookahead (?!.\1{10,}) is broken because:
- The
\1backreference refers to a capture group that doesn't exist yet when the lookahead runs. Lookaheads execute before the main pattern starts matching, so there's no captured value to reference here. That's why111-111-1111still matches—it's like the lookahead isn't even there.
The Correct Solution
We need to adjust the lookahead to first isolate the digits in the phone number, then check if any digit repeats 10 or more times. Here's the final regex:
^(?!.*(\d)\1{9,})(1-)?\d{3}-\d{3}-\d{4}$
How This Works
Let's break it down piece by piece:
- Negated Lookahead:
(?!.*(\d)\1{9,}).*matches any characters (including the hyphens in your phone format) to skip past non-digit characters.(\d)captures a single digit.\1{9,}checks if that same digit repeats at least 9 more times (for a total of 10+ identical digits across the entire number).- If this pattern is found, the lookahead fails, and the entire regex rejects the phone number.
- Main Phone Format Pattern:
(1-)?\d{3}-\d{3}-\d{4}$- Keeps your original valid format rules: either
nnn-nnn-nnnnor1-nnn-nnn-nnnn.
- Keeps your original valid format rules: either
Test Cases
- Valid Matches:
123-456-78901-987-654-3210
- Invalid Matches (Blocked):
111-111-1111(10 identical digits)1-222-222-2222(11 identical digits)333-333-3333(10 identical digits)
Key Takeaway
When using backreferences in lookaheads, make sure the capture group is defined inside the lookahead (or the lookahead can access it). Your original attempt tried to reference a capture group from the main pattern before it was ever captured, which is why it didn't work.
内容的提问来源于stack exchange,提问作者RedAuerbach
相关产品推荐
相关产品推荐

