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

正则表达式重复捕获组并忽略指定字符串问题求助

Fixing Your Regex to Capture Multiple Stream #x:x Entries

Let's break down what's wrong with your current regex and fix it to capture both Stream #0:4 and Stream #0:5 while ignoring the intermediate -> #0:0 (copy) content.

What's Wrong with the Original Regex?

Your regex /(?<=Stream mapping:)(\s+)([a-zA-Z])+(\s+)#([0-9]:[0-9])/s has a few key issues:

  • The ([a-zA-Z])+ capture group only captures the last letter of the word it matches (in this case, "m" from "Stream") because the + quantifier makes the group repeat, but only stores the final iteration.
  • It doesn't account for the intermediate -> #x:x (copy) content that sits between your target entries.
  • It captures unnecessary whitespace groups, cluttering your results.

The Solution

To capture all Stream #x:x entries after Stream mapping: and ignore the copy-related content, use a global match on the pattern that directly targets your desired format.

Regex Pattern

/Stream #\d:\d/g

How It Works

  • Stream #: Matches the literal prefix of your target entries.
  • \d:\d: Matches the digit-colon-digit format (e.g., 0:4, 0:5).
  • The g modifier enables global matching, so it finds all occurrences of the pattern in your text.

Example Usage (PHP)

$input = "Stream mapping: Stream #0:4 -> #0:0 (copy) -> #0:1 (copy) Stream #0:5";
preg_match_all('/Stream #\d:\d/', $input, $matches);
print_r($matches[0]);

Output

Array
(
    [0] => Stream #0:4
    [1] => Stream #0:5
)

If You Need a Single Regex with Capture Groups (For Non-Global Scenarios)

If you want a regex that directly captures both entries in groups (without relying on global matching), use this pattern with the s modifier (to make . match newlines):

/(?<=Stream mapping:).*?(Stream #\d:\d).*?(Stream #\d:\d)/s
  • (?<=Stream mapping:): Ensures we start matching right after the "Stream mapping:" prefix.
  • .*?: Non-greedily matches any characters (including newlines, thanks to s) until it hits the first target entry.
  • (Stream #\d:\d): Captures the first target entry.
  • The second .*? skips the intermediate copy content, and the final capture group grabs the second entry.

This will give you exactly the two captured groups you're looking for.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:19:40