You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中Regex匹配模块与序列号失败求助(Regex101可运行)

问题修正:Python中re.match无法匹配正则的问题

核心原因是re.match()仅从字符串起始位置尝试匹配,而你在regex101中测试的正则应该是针对字符串任意位置的内容,这直接导致代码中匹配失效。解决思路是改用支持任意位置匹配的re.search()或re.findall(),以下是修正后的完整代码示例:

import re
import os

# 替换为你的目标目录路径
target_directory = "./your_target_dir"
# 替换为你在regex101上验证通过的正则表达式(注意用raw字符串r''避免转义问题)
regex_pattern = re.compile(r'(\w+):.*System\.SerialNumber=(\d+)')

# 遍历目录下的*TxtMsg文件
for file_name in os.listdir(target_directory):
    if "TxtMsg" in file_name:
        full_path = os.path.join(target_directory, file_name)
        with open(full_path, 'r', encoding='utf-8') as file:
            # 读取文件内容,若文件过大可改为逐行读取
            file_content = file.read()
            # 提取所有匹配的模块名和序列号
            results = regex_pattern.findall(file_content)
            for module, serial in results:
                print(f"{module}: {serial}")

关键注意事项:

  • 正则表达式务必使用Python的raw字符串(前缀r),确保和regex101中的写法完全一致,避免转义字符冲突。
  • 若单文件内容较大,建议逐行处理以节省内存:将file_content = file.read()替换为for line in file: regex_pattern.findall(line)。
  • 如果你坚持要用re.match(),则必须保证目标匹配内容位于文件内容的最开头,否则无法命中,这种场景下不推荐使用re.match()。

内容的提问来源于stack exchange,提问作者Sanjeev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 15:06:17