首页 > 解决方案 > 从同一个文件python中找到两个匹配的模式

问题描述

我有一个包含 1000 行的文件,我需要在其中找到匹配的模式,一旦我找到并需要从那里找出下一个匹配模式,而不是从一开始

例子:

match1= Unlock event detected
match2= presence service not connected

.....
.....
10:12:53,presence service not connected
.....
.....
11:12:53, Unlock event detected ----> Matching pattern
.....
.....
11:13:53, presence service not connected ----> next matching pattern 
.....
.....

我需要得到 11:12:53 和 11:13:53 而不是 10:12:53

# Collect the list of hits
list_log = []
# opening the file
with open (file,'r', errors='ignore') as f:
    lines = f.read().splitlines()
#for loop and find the matching pattern
    for l in lines:
        if re.findall(r"Unlock event detected", l):
            list_log.append(l)
        elif re.findall(r'presence service not connected',l):
            list_log.append(l)
    for ll in list_log:
        print(ll)

标签: python

解决方案


要进入 list_log 您想要的两行,您只需要在登录时放置额外的条件。

import re

list_log = []
# opening the file
with open (file,'r', errors='ignore') as f:
    lines = f.read().splitlines()

    # find the matching patterns
    for l in lines:
        if not list_log and re.findall(r"Unlock event detected", l):
            list_log.append(l)
        elif list_log and re.findall(r'presence service not connected',l):
            list_log.append(l)
            break

    print(*list_log, sep = "\n")

输出(使用您的数据作为文件)

11:12:53, Unlock event detected ----> Matching pattern
11:13:53, presence service not connected ----> next matching pattern

推荐阅读