[Python] How to use a Python regular expression which depends on pre-initialised...

Discussão em 'Python' iniciado por Stack, Julho 29, 2025.

  1. Stack

    Stack Membro Participativo

    I want to have a regular expression which includes back-references to strings it hasn't actually seen in the current string.

    That is, I've already figured out what the literal values of the references should be, but they keep changing at run-time, so if I were to dynamically insert them into the regular expression then I would have to recompile the regular expression over and over as they changed.

    What I've tried to do instead is to dynamically rebuild the string being searched, and then append an initialiser to the regular expression (the initialiser shouldn't change, so it can be memoised).

    import re

    def rematch(pattern, string, **kwargs):
    unique = "pvDXpEvWblv93xul19ejlQ"

    initlist = [ f"{k}='(?P<{k}>.*)'" for k in kwargs.keys() ]
    pattern = f"{', '.join(initlist)}:{unique}:" + pattern

    initlist = [ f"{k}='{v}'" for k, v in kwargs.items() ]
    string = f"{', '.join(initlist)}:{unique}:" + string
    return re.match(pattern, string)


    I could formalise this better to guarantee memoisation of the compilation, but this is just illustrative.

    And it seems to work:

    example = re.match(
    r"(?P<first>\w*)\s+(?P<second>\w*)\s+(?P<third>\w*)",
    "alpha beta gamma"
    )

    example2 = rematch(
    r"(?P=third)\s*,\s*(?P=second):\s+(?P=animal)\s+(?P<also>\w*)",
    "gamma, beta: penguin chalk",
    animal="penguin",
    **example.groupdict())
    print(example2.groupdict())


    But is there a better, cleaner way? This implementation has a lot of warts. It only works for match(), while search() would need a different regex, for example.

    Continue reading...

Compartilhe esta Página