[Python] How to capture all values in a regex while matching a specific pattern? [duplicate]

Discussão em 'Python' iniciado por Stack, Maio 3, 2025.

  1. Stack

    Stack Membro Participativo

    Problem


    I would like to match strings following this pattern:

    prefix (value 0) (value 1) (value 2)


    with one or more text values, and get a list of all values. (here: ['value 0', 'value 1', 'value 2'])

    Possible solution


    One way to do this, using re:

    import re

    text = ... # some string

    if re.match(r"prefix (\([\w ]*\))+", text):
    values = re.findall(r"\(([\w ]*)\)", text)
    print(len(values), "values found:")
    for value in values:
    print('-', value)
    else:
    print("No match for:", text)

    Question


    My approach looks greedy, since it has to match the string twice. Is there a more elegant way to do this? I'm not sure if re is the right tool for that actually.

    Note that I am not looking for a repeated capture of a pattern with re.match (I know that there is none).

    Continue reading...

Compartilhe esta Página