正则表达式重复捕获组并忽略指定字符串问题求助
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
gmodifier 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 tos) 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

