Python使用正则遍历文件提取字段:匹配事件ID并关联输出对应时间
问题核心修正点
- 正则规则错位:原有事件ID正则从闭合标签
/EventID反向匹配数字,无法正确捕获标签内嵌的ID值;时间提取正则没有锚定 SystemTime属性边界,匹配范围混乱。 - 关联逻辑断裂:原有逻辑对ID、时间分别做两次全局正则匹配,生成两个独立列表,既无法保证顺序对齐,打印时也会把整个时间列表全部输出,无法实现单个ID对应单个时间的绑定。
- 变量污染问题:原代码用
event_id作为循环变量覆盖了外层定义的列表,后续取值会出现类型错误。
调整实现方案
正则规则优化
改为单次遍历匹配完整事件块,在同一条匹配结果中同时捕获对应事件ID和时间,从根源上避免错配,规则适配源文件中标签换行、带属性的格式:
event_block_regex = r'<EventID[^>]*>(?P<event_id>\d+)</EventID>\s*<TimeCreated\s+SystemTime="(?P<event_time>[^"]+)"'
完整可运行代码
保留原有定义的event_id、event_date列表存储提取结果,调整匹配逻辑实现ID与时间的一一绑定,输出格式完全对齐要求:
import os import re evtxlogs = '/home/user/evtx_logs/' event_id = [] event_date = [] eventdict = {'1102': {'count': 0}, '4611': {'count': 0}, '4624': {'count': 0}} for dirpath, dirnames, filenames in os.walk(evtxlogs): for xml_file in filenames: if not xml_file.lower().endswith('.xml'): continue with open(os.path.join(dirpath, xml_file), 'r') as f: data = f.read() # 逐块匹配事件,每个匹配结果自带绑定的ID和时间 for block in re.finditer(event_block_regex, data): current_id = block.group('event_id') current_time = block.group('event_time') # 将提取结果存入要求的存储列表 event_id.append(current_id) event_date.append(current_time) # 命中目标字典时按格式输出 if current_id in eventdict: print(f"Matched ID: {current_id}") print(f"Date and time of event: {current_time}") # 匹配条目间空行,对齐目标输出格式 print()
输出验证
按照提供的源文件格式,程序输出会完全符合预设效果:
Matched ID: 1102 Date and time of event: 2019-08-27 17:16:28.543879 Matched ID: 4611 Date and time of event: 2019-08-27 12:14:08.573156
内容的提问来源于stack exchange,提问作者Melany
相关产品推荐
相关产品推荐

