[Python] Python regex substitution for comma match

Discussão em 'Python' iniciado por Stack, Março 4, 2025.

  1. Stack

    Stack Membro Participativo

    For the input string as shown below, I am trying to substitute UK1/ after Street and every , and skip hyphen to create expected output shown below.

    Input = Street1-2,4,6,8-10

    Expected output = StreetUK/1-2,UK/4,UK/6,UK/8-10

    With the regex pattern I have trouble substitute for each captured group. How can I capture all the required groups for every , and sub required string.


    replacements = []
    pattern = r"(Street)?(?:\d+)(((,)?(?:\d+))*[-]?(?:\d+))*"

    def replacement(x):
    replacements.append(f"{x.group(1)}{'UK'}/")

    input = 'Street1-2,4,6,8-10'
    m = re.sub(pattern, replacement, input)
    print(m, [''.join(x) for x in replacements] )



    The above code just prints ['StreetUK/'] but not as expected.

    Continue reading...

Compartilhe esta Página