Search code examples
pythonregextoml

How can I Modify the parameter values in the specified fields in the toml file using the regular expression


I want to Modify the parameter values in the specified fields in the toml file using the regular expression In Python language. For example exchanging the value of name in [tool.poetry] field not in [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 code:

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)

Run the code, It changes the value in two places [tool.poetry] and [tool.pytest.ini_options], but I just want to change the value of name in [tool.poetry]. How to write the regular expression reg_name ? Thank you. 😊


Solution

  • You might use:

    (\[tool\.poetry](?:\n(?!\[[^][]*]).*)*\nname = ")[^"\n]*(?=")
    
    • ( Capture group 1
      • \[tool\.poetry]
      • (?:\n(?!\[[^][]*]).*)* Match all lines that do not start with [...]
      • \nname = " Match a newline and then name = "
    • ) Close group 1
    • [^"\n]* Match optional chars other than " or a newline
    • (?=") Assert " to the right

    In the replacement use the capture group 1 value:

    \1nameofproject
    

    See a regex demo and a Python demo.