Skip to content

Instantly share code, notes, and snippets.

@chuongmep
Created November 22, 2022 07:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chuongmep/e8c25ec2796b58ad8d6cea4b05fbe128 to your computer and use it in GitHub Desktop.
Save chuongmep/e8c25ec2796b58ad8d6cea4b05fbe128 to your computer and use it in GitHub Desktop.
import regex as re
# pattern match correct with string datetime format dd/mm/yyyy
pattern = re.compile(r'^(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[012])/((19|20)\d\d)$')
# pattern = re.compile(r'(\d{1,2})/(\d{1,2})/(\d{2,4})')
# test list of dates
test_dates = ['01/01/2019', '01/01/19', '21/11/22', '01/01/2019', '01/01/2019 01:01:01', '01/01/19 01:01:01', '1/1/2019 01:01:01', '1/1/19 01:01:01']
print("Test for correct dates with dd/mm/yyyy format")
# check if match
for date in test_dates:
if pattern.match(date):
print('Match: {}'.format(date))
else:
print('No Match: {}'.format(date))
# pattern match correct with string datetime format dd/mm/yy
pattern2 = re.compile(r'^(0[1-9]|[12][0-9]|3[01])/(0[1-9]|1[012])/(\d\d)$')
# check if match
print("test for correct dates with dd/mm/yy format")
for date in test_dates:
if pattern2.match(date):
print('Match: {}'.format(date))
else:
print('No Match: {}'.format(date))
print("Test match with dd/mm/yyyy and dd/mm/yy format")
for date in test_dates:
if pattern.match(date) or pattern2.match(date):
print('Match: {}'.format(date))
else:
print('No Match: {}'.format(date))
# pattern sequence starting by prefix C,P,T,R,I and sequence number 2 digits
pattern = re.compile(r'[C,P,T,R,I]\d{2}')
# test list
test = ['C01','P02','TS3','RNB4','I05']
# check if match
print("Test with sequence starting by prefix C,P,T,R,I")
for t in test:
if pattern.match(t):
print('Match: {}'.format(t))
else:
print('No Match: {}'.format(t))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment