开发者社区> 问答> 正文

如何在头上做非贪婪的正则表达式

这是一个字符串例如

Clone into repo1...
some text
Clone into repo2...
some text
Clone into repo3...
some text
fatal: Some exception was thrown.

我正在尝试获取最后的“克隆到repo3”和致命消息。这是我正在写的正则表达式:(Clone into。+ fatal:。+?$)with flags,re.DOTALL和`re.MULTILINE

但是我得到了全部信息。我知道以某种方式我们可以做到这一点。* Clone into。+ fatal:。+?$),但是我要处理的文本确实很大,如果在前面使用。*`将会花费大量时间。

谢谢大家的帮助!

编辑

我正在寻找一种正则表达式方式,因为我几乎有十个正则表达式,而且我不知道会匹配哪个正则表达式。

这是我编写的框架:

# Here's almost 10 compiled regex, some of them have this duplicated issue.
regex_list = [...]

for regex in regex_list:
    res = regex.findall(log_text)
    if res:
        reason = res[0]
        break

如果用正则表达式无法解决这个问题,也许我会重新考虑将所有这些正则表达式更改为一个通用函数,然后先执行rsplit。

顺便说一句,rsplit方法需要在引发致命错误后停止测试。如果在引发致命错误后测试仍保持运行,则此方法将与异常不匹配...

问题来源:stackoverflow

展开
收起
is大龙 2020-03-23 16:59:33 478 0
1 条回答
写回答
取消 提交回答
  • 对于长文本,首先拆分然后匹配所需的结果在子字符串中可能是有意义的。例如:

    import re
    
    text = """
        Clone into repo1...
        some text
        Clone into repo2...
        some text
        Clone into repo3...
        some text
        fatal: Some exception was thrown.
        """
    
    # Get the part after the last 'Clone into '
    end = text.rsplit("Clone into ", 1)[1]
    # Capture clone and fatal messages.
    match = re.search(r'\A(.\*\r?\n[\s\S]\*\b(fatal: .\*', end)
    # Fetch captures, if there are any.
    groups = None if match is None else match.groups()
    
    print(groups)
    

    输出:

    ('repo3...', 'fatal: Some exception was thrown.')
    

    如果您仍然需要短语“ Clone into`,请在使用第一个捕获组时在其前面添加前缀。整个过程可以用子字符串更优雅地完成,但是语法使我无所适从。

    回答来源:stackoverflow

    2020-03-23 16:59:37
    赞同 展开评论 打赏
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载