Home > Software engineering >  Regex for a string like "Date: 01Jan2022"
Regex for a string like "Date: 01Jan2022"

Time:06-23

I'm trying to find a string that looks like: "Date: 01JAN2022" where the date portion can be DDMMMYYYY. How do you write a regex for that in python?

CodePudding user response:

Assuming that the abbreviated month would always be three letters, you could simply use:

inp = ["01JAN2022", "blah"]
for i in inp:
    if re.search(r'^\d{2}[A-Z]{3}\d{4}$', i):
        print("Found a date: "   i)
    else:
        print("Not a date:   "   i)

To be more precise, we could use an alternation containing all 12 abbreviated months:

inp = ["01JAN2022", "blah"]
regex = r'^\d{2}(?:JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)\d{4}$'
for i in inp:
    if re.search(regex, i):
        print("Found a date: "   i)
    else:
        print("Not a date:   "   i)
  • Related