Skip to content

Instantly share code, notes, and snippets.

@crunk1
Last active November 3, 2020 02:25
Show Gist options
  • Save crunk1/81ac444b727b0f11dfd6f7adad1ee017 to your computer and use it in GitHub Desktop.
Save crunk1/81ac444b727b0f11dfd6f7adad1ee017 to your computer and use it in GitHub Desktop.
RFC3339 regexes - with day checking including leap years!
# https://tools.ietf.org/html/rfc3339
# https://en.wikipedia.org/wiki/Leap_year
## LEAP YEARS ##
# From wikipedia: "Every year that is exactly divisible by four is a leap year,
# except for years that are exactly divisible by 100, but these centurial years
# are leap years if they are exactly divisible by 400. For example, the years 1700,
# 1800, and 1900 are not leap years, but the years 1600 and 2000 are."
#
# Therefore, the following years are leap years:
# - [0-9][0-9][02468][48] // divisible by 4, but not by 100
# - [0-9][0-9][13579][26] // divisible by 4, but not by 100
# - [02468][048]00 // divisible by 400
# - [13579][26]00 // divisible by 400
## 30-DAY MONTHS ##
# April, June, September, November (04, 06, 09, 11)
## STARTING REGEX IN PCRE (NON-OPTIMIZED, READABILITY EMPHASIZED; REMOVE NEWLINES, WHITESPACE, AND COMMENTS)
^(
[0-9][0-9][0-9][0-9]-( // Non-leap-year matching.
(0[13578]|1[02])-(0[1-9]|[1-2][0-9]|3[0-1])| // 31 day month matching.
(0[469]|11)-(0[1-9]|[1-2][0-9]|30)| // 30 day month matching.
02-(0[1-9]|1[0-9]|2[0-8]) // 28 day February matching.
)|
([0-9][0-9](0[48]|[2468][048]|[13579][26])|[02468][048]00|[13579][26]00)-02-29 // Feb 29 on a leap year matching.
)
(T|t)([0-1][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](\.[0-9]+)? // Time matching.
(Z|z|(\+|\-)([0-1][0-9]|2[0-3]):[0-5][0-9])$ // Time offset matching.
## SINGLE LINE PATTERNS ##
# PCRE/Python/Golang/RE2
^([0-9][0-9][0-9][0-9]-((0[13578]|1[02])-(0[1-9]|[1-2][0-9]|3[0-1])|(0[469]|11)-(0[1-9]|[1-2][0-9]|30)|02-(0[1-9]|1[0-9]|2[0-8]))|([0-9][0-9](0[48]|[2468][048]|[13579][26])|[02468][048]00|[13579][26]00)-02-29)(T|t)([0-1][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](\.[0-9]+)?(Z|z|(\+|\-)([0-1][0-9]|2[0-3]):[0-5][0-9])$
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment