从同一个文件中找到两个匹配的模式

2024-04-24 23:21:28 发布

您现在位置: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)

Tags: theeventlogforservice模式notlist
1条回答
网友
1楼 · 发布于 2024-04-24 23:21:28

要进入list\u 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

相关问题 更多 >