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

Python正则匹配:捕获以TASK开头且含.retry结尾的多段分组

Solution to Capture Failed TASK Blocks Ending with .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 the TASK keyword 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 .retry at 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 10:06:58