In [1]:
import re
In [2]:
pattern = re.compile(r'''
^
(?P<year>\d{4})
(?P<delimiter>[- /])
(?P<month>\d{1,2})
(?P=delimiter) # must match earlier delimiter
(?P<day>\d{1,2})
$
''', re.VERBOSE)
In [3]:
foo = [
'2016-7-6',
'2016-07-06',
'2016 07-06',
'2016 07 06',
'2016/07 06',
'2016/07/06',
'2016-07/06',
]
In [4]:
for s in foo:
print('%r ' % s, end='')
m = re.match(pattern, s)
if not m:
print('no match')
continue
print(
'year=%s, month=%s, day=%s delimiter=%r' % (
m.group('year'),
m.group('month'),
m.group('day'),
m.group('delimiter'),
))