HomeSoftware EngineeringFind out how to write a validDate Regex in Python

Find out how to write a validDate Regex in Python

The problem

Your job is to jot down an everyday expression (regex) that may match a string provided that it accommodates at the least one legitimate date, within the format [mm-dd] (that’s, a two-digit month, adopted by a splash, adopted by a two-digit date, surrounded by sq. brackets).

You must assume the yr in query is not a intercalary year. Due to this fact, the variety of days every month ought to have are as follows:

    1. January – 31 days
    1. February – 28 days (leap years are ignored)
    1. March – 31 days
    1. April – 30 days
    1. Might – 31 days
    1. June – 30 days
    1. July – 31 days
    1. August – 31 days
    1. September – 30 days
    1. October – 31 days
    1. November – 30 days
    1. December – 31 days

All textual content exterior a sound date might be ignored, together with different invalid dates.


"[01-23]" # January twenty third is a sound date
"[02-31]" # February thirty first is an invalid date
"[02-16]" # legitimate
"[ 6-03]" # invalid format
"ignored [08-11] ignored" # legitimate
"[3] [12-04] [09-tenth]" # December 4th is a sound date

The answer in Python code

Choice 1:

import re

valid_date = re.compile(r"[("
    # Jan, Mar, May, Jul, Aug, Oct, Dec: 31 days
    # Feb: 28 days
    # Apr, Jun, Sep, Nov: 30 days

Choice 2:

import datetime
from re import compile

class check_date(object):

    def __init__(self):
        self._rgxp = compile(r'(?P<date>[d{2}-d{2}])')

    def search(self, string):
        date = None
        search_date =
            date = datetime.datetime.strptime('date'), "[%m-%d]")
        besides BaseException:

        if date: return

valid_date = check_date()

Choice 3:

valid_date = compile('[((?!02-(?:29|30))(?:0[1-9]|1[012])-(?:0[1-9]|1[0-9]|2[0-9]|30)|(?:0[13578]|1[02])-31)]')

Take a look at circumstances to validate our resolution

take a look at.describe("Fundamental checks")
take a look at.anticipate("[01-23]")!=None, "January twenty third is a sound date")
take a look at.anticipate("[02-31]")==None, "February thirty first is an invalid date")
take a look at.anticipate("[02-16]")!=None , "legitimate")
take a look at.anticipate("[ 6-03]")==None, "invalid format")
take a look at.anticipate("ignored [08-11] ignored")!=None, "legitimate")
take a look at.anticipate("[3] [12-04] [09-tenth]")!=None, "December 4th is a sound date")
take a look at.anticipate("[02-00]")==None, "invalid format")
take a look at.anticipate("[[[08-29]]]")!=None, "legitimate")
take a look at.anticipate("[13-02]")==None, "invalid format")
take a look at.anticipate("[02-[08-11]04]")!=None, "legitimate")

Most Popular

Recent Comments