[Python] Match 2 strings then print both matches

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

  1. Stack

    Stack Membro Participativo

    I have 2 lists that i want to match and then print the matched values from both list A and list B

    import re

    A="""
    ABB1265 DUE blah blah
    ADD809 DUE blah blah
    blah ADD blah
    TIME 20:33 ADD223 blah blah.
    """

    B = """
    GFA
    ADD
    ABB
    TI
    """



    pattern = re.compile("(" + "|".join(i.strip() for i in B.strip().splitlines()) + ")")
    for line in A.splitlines():
    line = line.strip()
    m = pattern.match(line) #Using re.match
    if m:
    print(line,end=",")
    print(m.group(1))


    This code is matching only words at the start of the line and it also taking strings inside strings

    the output currently is this:

    ABB1265 DUE blah blah,ABB
    ADD809 DUE blah blah,ADD
    TIME 20:33 ADD223 blah blah.,TI


    My ideal output is this:

    ABB1265 DUE blah blah,ABB
    ADD809 DUE blah blah,ADD
    blah ADD blah,ADD
    TIME 20:33 ADD223 blah blah.,ADD

    Continue reading...

Compartilhe esta Página