[Python] Regex issue not finding third group of characters [closed]

Discussão em 'Python' iniciado por Stack, Abril 7, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to decode a string to validate its contents. The string should contain a date formatted as mm/dd/yy, a space, a two letter code, a space, a three digit code, a space, and finally a single character code. I have written this test code for reference. The first test is the complete regex pattern, the second and third are the first two groups of characters, and the fourth test is where it fails to find the two character code. Assistance please!

    import re

    pattern = r'^(\d{2}/\d{2}/\d{2})\s((GHNO){2})\s(\d\d\d)\s([A-Z])'
    date_pattern = r'^(\d{2}/\d{2}/\d{2})\s'
    date_breed_pattern = r'^(\d{2}/\d{2}/\d{2})\s([GHNO]{2})\s'
    date_breed_farm_pattern = r'^(\d{2}/\d{2}/\d{2})\s([GHNO]{2})\s\d'


    whole = re.compile(pattern)
    dateonly = re.compile(date_pattern)
    datebreed = re.compile(date_breed_pattern)
    datebreedfarm = re.compile(date_breed_farm_pattern)


    test_list = ("01/01/24 HH 121 S",
    "11/18/24 NN 097 A",
    "1/1/2024 h 21 A",
    "1/01/24 HH 021 S",
    "10/01/24 OH 023 T",
    "01/01/24 HH 021 R"
    )

    print("Pattern = ", pattern)
    print("date_pattern = ", date_pattern)
    print("date_breed_pattern = ", date_breed_pattern)
    print("date_breed_farm_pattern = ", date_breed_farm_pattern)
    print("---------------------\n")

    print("\nPattern test")
    for i in test_list:
    match = re.match(whole, i)
    print(i, match)


    print("\nDate_pattern test")
    for i in test_list:
    match = re.search(dateonly, i[:9])
    print(i, match)

    print("\nDate_Breed_pattern test")
    for i in test_list:
    match = re.search(datebreed, i[:12])
    print(i, match)

    print("\nDate_Breed_Farm_pattern test")
    for i in test_list:
    match = re.search(datebreedfarm, i[:12])
    print(i, match)

    Continue reading...

Compartilhe esta Página