[Python] How to skip, if starts with, but match other strings

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

  1. Stack

    Stack Membro Participativo

    I want to match and substitute for strings as shown in example below, but not for some strings which start with test or !!. Have used negative lookahead to skip matching unwanted strings but (Street|,)(?=\d) matching for Street & comma replacing group 1 with UK/ is not working as expected.

    import re
    input = [ 'Street1-2,4,6,8-10',
    '!! Street4/31/2',
    'test Street4' ]
    pattern = r'(^(?!test\s|!!\s).*(Street|,)(?=\d))'
    output = [re.sub(pattern, r'\g<1>UK/', line) for line in input ]


    Actual output:

    ['Street1-2,4,6,UK/8-10', '!! Street4/31/2', 'test Street4']


    Expected output:

    ['StreetUK/1-2,UK/4,UK/6,UK/8-10', '!! Street4/31/2', 'test Street4']

    Continue reading...

Compartilhe esta Página