Skip to main content
 首页 » 编程设计

python之正则表达式 block 中的正则表达式

2024年09月03日29虾米姐

我一直在尝试解析 block 中的值。

让我用一个例子来解释。

我有以下文字:

started xx xxxxxxx xxxxx xxxxxx xx xxxxxxxxx xxxxxxx xxxx xx 
xx xxx xxxxx xxxx xxxxxxxx xxxx xxxxxx found 9999 xxxxx xxxxx 
xxx xx xxxx xxxx xxxxxxxxxxx xxxxxxx xxx stored 9999 finished 

我试图捕捉“开始”和“完成”之间的值

我试过这样的

(?<block>started(.|\n)*finished) 

但我不知道如何在“已存储”附近添加值 \d+?

请您参考如下方法:

您提供的正则表达式不适用于 Python re , 作为 (?<block>...)不是受支持的命名组语法,它必须类似于 (?P<block>...) .

此外,建议避免 (.|\n)*这是一个非常低效的结构,使用 .*?与 re.DOTALL/re.S或 (?s)反而。

如果您需要在 stored 之后的数字旁边捕获数字和之前 finished (如果这是可选的)使用

re.findall(r'started(.*?(?:stored\s+(\d+)\s+)?)finished', text, re.S) 

参见 regex demo

详情

  • started - 左手定界符
  • (.*?(?:stored\s+(\d+)\s+)?) - 第 1 组:
    • .*? - 任何 0+ 个字符,尽可能少
    • (?:stored\s+(\d+)\s+)? - 一个可选的组匹配
      • stored\s+ - stored和 1+ 个空格
      • (\d+) - 第 2 组:一个或多个数字
      • \s+ - 1+ 个空格
  • finished - 右手定界符。