MST

星途 面试题库

面试题:Python正则表达式条件匹配的优化与嵌套应用

在一个复杂的日志文件文本中,存在以下几种格式的记录:1. 'LOG_INFO_时间戳_具体信息',其中'时间戳'格式为YYYY - MM - DD HH:MM:SS,'具体信息'是除换行符外的任意字符组合;2. 'LOG_ERROR_模块名_错误码_时间戳_错误详情','模块名'由字母和数字组成,'错误码'是三位数字,'时间戳'格式同上,'错误详情'是除换行符外的任意字符组合。要求使用Python正则表达式进行匹配,并且要考虑到效率优化,以最快速度提取出所有'LOG_ERROR'记录中的'模块名'、'错误码'、'时间戳'和'错误详情',以及所有'LOG_INFO'记录中的'时间戳'和'具体信息'。请写出完整的实现代码,并解释关键步骤和优化思路。
27.6万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
import re


def parse_log(log_text):
    log_info_pattern = re.compile(r'LOG_INFO_(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})_(.*)')
    log_error_pattern = re.compile(r'LOG_ERROR_([A-Za-z0-9]+)_(\d{3})_(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})_(.*)')

    log_info_results = []
    log_error_results = []

    for line in log_text.splitlines():
        info_match = log_info_pattern.match(line)
        if info_match:
            timestamp, details = info_match.groups()
            log_info_results.append((timestamp, details))

        error_match = log_error_pattern.match(line)
        if error_match:
            module_name, error_code, timestamp, error_details = error_match.groups()
            log_error_results.append((module_name, error_code, timestamp, error_details))

    return log_info_results, log_error_results


# 示例使用
log_text = """
LOG_INFO_2023-10-01 12:00:00_This is an info log
LOG_ERROR_module1_123_2023-10-01 12:01:00_Error details here
"""
info_results, error_results = parse_log(log_text)
print("LOG_INFO记录:", info_results)
print("LOG_ERROR记录:", error_results)

关键步骤解释

  1. 定义正则表达式
    • log_info_pattern用于匹配LOG_INFO格式的记录。(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})捕获时间戳,(.*)捕获具体信息。
    • log_error_pattern用于匹配LOG_ERROR格式的记录。([A-Za-z0-9]+)捕获模块名,(\d{3})捕获错误码,(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})捕获时间戳,(.*)捕获错误详情。
  2. 遍历日志文本
    • 使用splitlines()方法按行分割日志文本,这样可以逐行处理,减少内存占用。
    • 对每一行分别使用log_info_patternlog_error_pattern进行匹配。
    • 如果匹配成功,使用groups()方法获取捕获组的内容,并添加到相应的结果列表中。

优化思路

  1. 预编译正则表达式:使用re.compile()对正则表达式进行预编译,这样在多次匹配时可以提高效率。
  2. 逐行处理:通过splitlines()逐行读取日志文本,避免一次性加载整个大文件到内存,减少内存开销,并且在匹配时也能更快定位到目标记录。