You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

正则表达式优化:限制手机号格式并禁止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 \1 backreference 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 why 111-111-1111 still 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:

  1. 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.
  2. Main Phone Format Pattern: (1-)?\d{3}-\d{3}-\d{4}$
    • Keeps your original valid format rules: either nnn-nnn-nnnn or 1-nnn-nnn-nnnn.

Test Cases

  • Valid Matches:
    • 123-456-7890
    • 1-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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:06:56