python-regexHow to match a YYYY-MM-DD date with Python Regex?
Python Regex can be used to match a YYYY-MM-DD date. The following example code block shows how to do this:
import re
date_string = '2020-01-01'
date_regex = re.compile(r'(\d{4})-(\d{2})-(\d{2})')
match = date_regex.match(date_string)
if match:
print('Year:', match.group(1))
print('Month:', match.group(2))
print('Day:', match.group(3))
The output of the example code is:
Year: 2020
Month: 01
Day: 01
Code explanation
import re
: imports the Python Regex moduledate_string = '2020-01-01'
: sets the date string to matchdate_regex = re.compile(r'(\d{4})-(\d{2})-(\d{2})')
: compiles the Regex pattern to match the date stringmatch = date_regex.match(date_string)
: matches the date string with the Regex patternif match:
: checks if the date string matches the Regex patternprint('Year:', match.group(1))
: prints the year part of the date stringprint('Month:', match.group(2))
: prints the month part of the date stringprint('Day:', match.group(3))
: prints the day part of the date string
Helpful links
More of Python Regex
- How to replace all using Python regex?
- How to count matches with Python regex?
- How to match a year with Python Regex?
- How to perform a zero length match with Python Regex?
- How to use word boundaries in Python Regex?
- How to match whitespace in Python regex?
- How to match a hex number with regex in Python?
- How to match a UUID using Python regex?
- How to match a URL path using Python regex?
See more codes...