正则表达式搜索环视

Regex search lookaround

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

日志文件如下所示:

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 \|'.

很遗憾,它不起作用。

任何帮助都会很棒。

直觉上,人们会说匹配 ERROR 之前的最后一个 config file。使用较新的 regex 模块,变量 lookbehind 是可能的,如下所示:

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(点击Table)。


这里稍微解释一下:

(?<=             # 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 中的空格也需要转义,双引号 不需要 需要转义(使其仅在 Whosebug).
这仅适用于较新的 regex 模块,因为后视可以是任意长度。