如何使用正则表达式修改toml文件中指定字段的参数值
我想用Python语言通过正则表达式来修改toml文件中指定字段的参数值。比如说,我想交换[tool.poetry]字段里name
的值,而不想动[tool.pytest.ini_options]里的值。
[tool.poetry]
version = "0.1.0"
description = "python is good"
name = "template-python"
readme = "README.md"
packages =[
{include="projectname"}
]
[tool.poetry.dependencies]
python = ">=3.11,<3.13"
[tool.poetry.group.test.dependencies]
pytest = "^8.0.0"
[tool.pytest.ini_options]
pythonpath = "."
addopts = ["-v", "-s", "--import-mode=importlib"]
name = "hello"
Python代码:
def tereg():
with open('pyproject.toml', 'r', encoding='utf-8') as f:
r = f.read()
reg_name = r'(?<=name = ").*(?=")'
# reg_name = r'(\[tool\.poetry\][\s\S]*?)name = "(.*)"([\s\S]*?[(\r\n)|\n]\[.*?\])'
re.sub(reg_name, "nameofproject", r)
运行这段代码后,它会同时改变[tool.poetry]和[tool.pytest.ini_options]中的值,但我只想改变[tool.poetry]里的name
的值。那我该怎么写正则表达式reg_name
呢?谢谢。