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

如何用正则表达式区分单数字与多数字的重复数值模式?

Got it, let's fix this regex issue for you! The problem with your current pattern is that it doesn't explicitly enforce we're matching full, space-separated numeric values (and doesn't limit the digit count to 3 as you mentioned). Here's how to resolve it:

The Improved Regex

(?<=^| )(\d{1,3})(?: \1)+(?=$| )

If you need to include the surrounding spaces in the match (for replacement or other use cases), use this version instead:

(?:^| )(\d{1,3})(?: \1)+(?:$| )

Why Your Original Regex Failed

Your original pattern (\d+)( \1)+ has two critical gaps:

  1. No digit length constraint: \d+ matches any length of digits, but you specified values are at most 3 digits long.
  2. Missing boundary validation: While your string uses spaces to separate values, the original regex doesn't explicitly anchor each numeric term to its surrounding spaces or string edges. This leads to unexpected mixed matches (like the 1 and 11 overlap you saw) because it doesn't guarantee we're working with complete, standalone values.

How the New Regex Works

Let's break down each component:

  • (?<=^| ): A positive lookbehind that ensures we start at the string's beginning or right after a space—guaranteeing we're targeting the start of a full numeric value.
  • (\d{1,3}): The capture group for our numeric value, restricted to 1-3 digits to align with your requirement.
  • (?: \1)+: A non-capturing group that matches one or more repetitions of [space] + the exact captured value—this ensures we only match identical, space-separated values.
  • (?=$| ): A positive lookahead that ensures we end at the string's end or right before a space—guaranteeing we're targeting the end of a full numeric value.

Testing on Your Sample String

When you run this regex against your input string:

0 5 0 0 0 16 1 1 1 1 3 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 11 1 11 1 1 1 11 1 1 1 1 1 1 1 2 11 1 4 4 4 16

You'll get these accurate, non-overlapping matches:

  • 0 0 0
  • 1 1 1 1
  • The long consecutive run of single 1s (all the 1s before the first 11)
  • The shorter run of 1 1 1 later in the string
  • 4 4 4

Any consecutive 11 values (if present) would also be matched correctly, with no confusion or overlap with single 1s.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:08:10