【问题标题】:Match all "errors:" but not "errors: 0" [duplicate]匹配所有“错误:”但不匹配“错误:0”[重复]
【发布时间】:2020-07-02 11:33:13
【问题描述】:

我是 python 新手,不是在寻找“快速方法”,而是在寻找提示。

我想检查一个文件中是否存在模式“error:”并用行号打印出来,这样我以后就知道去哪里找了。但是,如果值为 0(表示“错误:0”),则不应触发。

这是我的“匹配所有错误:”脚本:

#!/usr/bin/env python

import re
import sys

lookup = 'errors: '
lookup2 = 'errors: 0'

with open(sys.argv[1]) as myFile:
    for num, line in enumerate(myFile, 1):
        if lookup in line:
            print('Line:', num, line)

我尝试了“不”的说法,但这不起作用:

#!/usr/bin/env python

import re
import sys

lookup = 'errors: '
lookup2 = 'errors: 0'

with open(sys.argv[1]) as myFile:
    for num, line in enumerate(myFile, 1):
        if lookup in line not lookup2:
            print('Line:', num, line)

有什么提示吗? 对不起,我可能非常基本的问题......

【问题讨论】:

    标签: python regex python-3.x match


    【解决方案1】:

    根据我的理解。如果存在字符串 errors: 但如果存在 errors: 0 则不要打印内容。

    with open(sys.argv[1]) as myFile:
        for num, line in enumerate(myFile, 1):
            if lookup in line and lookup2 not in line:
                print('Line:', num, line)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-03
      • 2011-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-05
      • 2020-05-01
      相关资源
      最近更新 更多