Skip to content

Instantly share code, notes, and snippets.

@harshithjv
Last active August 6, 2020 13:41
Show Gist options
  • Select an option

  • Save harshithjv/c58f0dfce0656cf94c8c to your computer and use it in GitHub Desktop.

Select an option

Save harshithjv/c58f0dfce0656cf94c8c to your computer and use it in GitHub Desktop.
Python Regex object to validate crontab entry time format string.
"""
Referred from stackoverflow question: http://stackoverflow.com/questions/235504/validating-crontab-entries-w-php
"""
validate_crontab_time_format_regex = re.compile(\
"{0}\s+{1}\s+{2}\s+{3}\s+{4}".format(\
"(?P<minute>\*|[0-5]?\d)",\
"(?P<hour>\*|[01]?\d|2[0-3])",\
"(?P<day>\*|0?[1-9]|[12]\d|3[01])",\
"(?P<month>\*|0?[1-9]|1[012])",\
"(?P<day_of_week>\*|[0-6](\-[0-6])?)"\
) # end of str.format()
) # end of re.compile()
validate_crontab_time_format_regex.match("* * * * *").groupdict()
# Output: {'minute': '*', 'hour': '*', 'day': '*', 'month': '*', 'day_of_week': '*'}
validate_crontab_time_format_regex.match("56 12 * * 4-6").groupdict()
# Output: {'minute': '56', 'hour': '12', 'day': '*', 'month': '*', 'day_of_week': '4-6'}
validate_crontab_time_format_regex.match(" * * * 4-6").groupdict()
"""
Error output since cron time string is invalid. Regex returns None and so 'groupdict()' method is not available :
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
/path/to/<ipython-input-55-2f96c699e4b7> in <module>()
----> 1 validate_cron_time_format_regex.match(" * * * 4-6").groupdict()
AttributeError: 'NoneType' object has no attribute 'groupdict'
"""
@x200595
Copy link
Copy Markdown

x200595 commented Aug 6, 2020

Hello they are a probleme for example if the crontab are:
0 7 * * 1,2,3,4,5,8
(validate_crontab_time_format_regex.match("0 7 * * 1,2,3,4,5,8").groupdict())

result:
{'minute': '0', 'hour': '7', 'day': '', 'month': '', 'day_of_week': '1'}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment