正则表达式b中的正则表达式

2024-09-29 17:18:43 发布

您现在位置:Python中文网/ 问答频道 /正文

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

让我用一个例子来解释。在

我有以下文字:

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

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

我试过这样的方法

^{pr2}$

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


Tags: 例子xxx文字finishedxxxxxxxstartedfound
1条回答
网友
1楼 · 发布于 2024-09-29 17:18:43

您提供的regex不能用于Pythonre,因为(?<block>...)不是受支持的命名组语法,它必须看起来像(?P<block>...)。在

另外,建议避免(.|\n)*这是一个非常低效的构造,请将.*?re.DOTALL/re.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-右分隔符。在

相关问题 更多 >

    热门问题