【问题标题】:Regex search lookaround正则表达式搜索环视
【发布时间】:2017-05-25 10:14:07
【问题描述】:

我为我编写的这个脚本生成了一个日志文件,我想查找错误。

日志文件如下所示:

24/05/2017 07:39:55 PM | DEBUG | Reading config file "FRGD-1_1.cfg". | main.py:81 - set_configparser()
...
...
24/05/2017 07:39:55 PM | DEBUG | Reading config file "FRGD-1_10.cfg". | main.py:81 - set_configparser()    
...
...
24/05/2017 08:39:55 PM | DEBUG | Reading config file "RFGD-1_5.cfg". | main.py:81 - set_configparser()    
...    
25/05/2017 09:53:47 PM | ERROR | KeyError. There is an issue with the config file for this download. Please check the config file for errors. | script.py:137 - main()    
...
... 
24/05/2017 10:39:55 PM | DEBUG | Reading config file "DPGD-4_15.cfg". | main.py:81 - set_configparser()  
...
...
24/05/2017 11:39:55 PM | DEBUG | Reading config file "ZXTD-3_1.cfg". | main.py:81 - set_configparser()
...  
25/05/2017 03:53:47 AM | ERROR | KeyError. There is an issue with the config file for this download. Please check the config file for errors. | script.py:137 - main()    
...
...
24/05/2017 07:39:55 PM | DEBUG | Reading config file "FRGD-1_1.cfg". | main.py:81 - set_configparser()
...
...  
24/05/2017 07:39:55 PM | DEBUG | Reading config file "FRGD-1_10.cfg". | main.py:81 - set_configparser()

我想捕获所有引发错误的配置文件的名称。

为了识别线条,我寻找具有以下特征的线条:

DD/MM/YYYY HH:MM:SS PM | DEBUG | Reading config file "<file_name>.cfg".

直接在之前:

DD/MM/YYYY HH:MM:SS PM | ERROR |

在上面的例子中,它们是“RFGD-1_5.cfg”和“ZXTD-3_1.cfg”。

我正在使用 Python 来运行这个正则表达式,因此我将整个文件连接到一行并使用了以下正则表达式

'(?<=Reading config file "(.{13})").+?\| ERROR \|'.

不幸的是,它不起作用。

任何帮助都会很棒。

【问题讨论】:

    标签: python regex regex-lookarounds regex-greedy


    【解决方案1】:

    直觉上,有人会说匹配ERROR 之前的最后一个config file。使用较新的 regex 模块,可以像这样进行变量后视:

    import regex as re
    rx = re.compile(r'''
                    (?<=config\ file\ "([^"]+)"(?s:.*?))
                    \|\ ERROR\ \|
                    ''', re.VERBOSE)
    
    print(rx.findall(string))
    # ['RFGD-1_5.cfg', 'ZXTD-3_1.cfg']
    

    a demo on regexstorm.com(点击表格)。


    这里稍微解释一下:
    (?<=             # a pos. lookbehind              
        config file  # config file literally
        \"([^\"]+)\" # capture anything between "..."
        (?s:.*?)     # turns on single line mode (dot matches all including newline), 
                     # lazily, expanded as needed
    )                # closing lookbehind
    \| ERROR \|      # | ERROR | literally 
    

    请注意,verbose mode 中的空格也需要转义,并且双引号 不需要 需要转义(使其仅在 StackOverflow 上很漂亮)。
    这仅适用于较新的 regex 模块,因为后视可以是任意长度。

    【讨论】:

    • 您好 Jan。感谢您的宝贵时间。这就像魔术一样有效。我能否请您澄清一下您在本节中所做的工作:(?s:.*?)
    • @jerry_doe:是的,请参阅修改后的答案。
    • 非常感谢 Jan。这太棒了。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-23
    • 1970-01-01
    • 2014-06-02
    • 2023-04-10
    • 2013-08-16
    • 1970-01-01
    相关资源
    最近更新 更多