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

验证非零1-3位数字逗号分隔列表的正则表达式问题

Fixing Your Regex for Comma-Separated Number Lists

Let's break down why your current regex is failing and fix it step by step.

What's Wrong with the Original Regex?

Your regex ^([1-9]|[0-9][1-9]|[0-9][0-9][1-9](?:,(?:[1-9]|[0-9][1-9]|[0-9][0-9][1-9]))*)$ has two critical issues:

  1. Broken Group Structure: The comma-separated repetition logic is only tied to the 3-digit number option. That means if your first element is a 1-digit or 2-digit number (like 44), the regex doesn't account for any subsequent values after the comma—this is exactly why 44,222,555 gets marked invalid.
  2. Overly Strict Digit Rules: Your 2-digit pattern [0-9][1-9] forces the second digit to be non-zero, so valid numbers like 90 or 10 get incorrectly rejected. Similarly, the 3-digit pattern [0-9][0-9][1-9] requires the third digit to be non-zero, ruling out valid entries like 120.

The Correct Regex

We can simplify this with a negative lookahead to block all-zero values, while fully supporting 1-3 digits (including leading zeros):

^(?!0{1,3})\d{1,3}(?:,(?!0{1,3})\d{1,3})*$

How It Works

Let's break down each component:

  • ^ → Anchors the match to the start of the string.
  • (?!0{1,3}) → Negative lookahead: Ensures the next 1-3 characters aren't all zeros (blocks 0, 00, 000).
  • \d{1,3} → Matches 1 to 3 digits (supports leading zeros like 01 or 005).
  • (?:,(?!0{1,3})\d{1,3})* → Non-capturing group that repeats for additional entries:
    • , → Matches the comma separator.
    • (?!0{1,3})\d{1,3} → Repeats the same valid number check as the first element.
    • * → Allows zero or more extra comma-separated numbers.
  • $ → Anchors the match to the end of the string.

Test Cases That Now Pass

  • Valid entries: 44,222,555, 90, 01, 001, 120, 5
  • Invalid entries: 0, 00, 000, 0,123, 123,000

内容的提问来源于stack exchange,提问作者NoBullMan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 07:48:14