如何用正则表达式区分单数字与多数字的重复数值模式?
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:
- No digit length constraint:
\d+matches any length of digits, but you specified values are at most 3 digits long. - 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
1and11overlap 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 01 1 1 1- The long consecutive run of single
1s (all the1s before the first11) - The shorter run of
1 1 1later 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

