正则表达式搜索环视

时间:2017-05-25 10:14:07

标签: python regex regex-lookarounds regex-greedy

我为此脚本生成了一个日志文件,我已经写好了,我想查找错误。

日志文件如下所示:

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 |

在上面的示例中,它们是&#34; RFGD-1_5.cfg&#34;和&#34; ZXTD-3_1.cfg&#34;。

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

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

不幸的是它不起作用。

任何帮助都会很棒。

1 个答案:

答案 0 :(得分:1)

直观地说,人们会说config file之前的最后ERROR。使用较新的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(点击)。

<小时/> 这里有一点解释:

(?<=             # 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模块,因为lookbehind可以是任意长度。