Python正则匹配:捕获以TASK开头且含.retry结尾的多段分组
Got it, let's fix your regex to precisely catch only the failed TASK blocks (those ending with .retry) without picking up the successful ones. Here's how to do it:
Final Regex Pattern
TASK \*{30,}(?:(?!TASK \*{30,}).)*?\.retry
Breakdown of the Pattern
Let's walk through each part so you understand how it works:
TASK \*{30,}: Matches the start of a TASK block, including theTASKkeyword and the long string of asterisks. The{30,}ensures we match at least 30 asterisks (adjust this number if your actual TASK markers have more or fewer stars—you could also use\*+for one or more asterisks if the exact count doesn't matter).(?:(?!TASK \*{30,}).)*?: This is the key part that prevents cross-block matching. The negative lookahead(?!TASK \*{30,})checks that the next character isn't the start of a new TASK block. The.*?is a non-greedy match, meaning it stops as soon as it hits the.retryat the end of the failed block.\.retry: Matches the exact failure marker at the end of the block. We escape the dot with\because dots have special meaning in regex (they match any character).
Handling Multiline TASK Blocks
If your TASK blocks include line breaks, add the DOTALL flag (or (?s) at the start of the regex) so the . matches newline characters too:
(?s)TASK \*{30,}(?:(?!TASK \*{30,}).)*?\.retry
Test with Your Example Text
When run against your sample string:
TASK ********************************** everything ok TASK ********************************** some text here until you get dot retry.retry TASK ********************************** everything ok
This regex will only capture the failed block:TASK ********************************** some text here until you get dot retry.retry
内容的提问来源于stack exchange,提问作者Mazimer

