如何用Python 3.9正则提取配置文件中等号后的内容?
解决Python正则提取配置文件中等号后内容的问题
问题场景
配置文件内容:
profile2.name=share2 profile8.name=share8 profile4.name=shareSSH profile9.name=share9
需要提取每行等号=后的内容,期望re.find_all()返回结果:
['share2', 'share8', 'shareSSH', 'share9']
之前使用正则^profile[0-9]\.name=(.*?)未得到预期结果,反而返回包含profileX.name=的内容。
原因分析
- 原正则的
.*?是非贪婪匹配,未明确匹配到行尾,容易出现匹配不完整的情况; - 未启用
re.MULTILINE标志,导致^仅匹配整个文本的开头,无法匹配每行的起始; [0-9]仅支持单个数字,若后续出现多位数的profile编号会失效。
解决方案
方案1:优化正则表达式
使用如下正则,并配合re.MULTILINE标志:
import re config_content = """profile2.name=share2 profile8.name=share8 profile4.name=shareSSH profile9.name=share9""" # 正则匹配:行起始匹配profile+数字+.name=,捕获后续所有内容到行尾 pattern = r'^profile\d+\.name=(.*)$' result = re.findall(pattern, config_content, re.MULTILINE) print(result)
输出结果:
['share2', 'share8', 'shareSSH', 'share9']
正则说明:
^:匹配每行的起始(需配合re.MULTILINE)profile\d+:匹配profile后接1个或多个数字(支持多位数编号)\.name=:匹配固定字符串.name=(.*)$:捕获等号后到行尾的所有内容,$确保匹配到每行结束
方案2:非正则实现(更简单)
对于这种简单的键值对格式,直接按行分割后拆分等号即可,无需正则:
config_content = """profile2.name=share2 profile8.name=share8 profile4.name=shareSSH profile9.name=share9""" result = [line.split('=')[1] for line in config_content.splitlines() if '=' in line] print(result)
输出结果与方案1一致,这种方式代码更直观,适合无复杂格式的配置文件。
内容的提问来源于stack exchange,提问作者buhtz
相关产品推荐
相关产品推荐

