Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีใช้ Python Regex จับคู่ Date String

กรณีแรก date string จับคู่รูปแบบ d-m-y กรณีที่สองไม่จับคู่

ตัวอย่าง

import re
datestring = '21-09-1991'
foo = re.match('(\d{2})[/.-](\d{2})[/.-](\d{4})$', datestring)
print(foo.group())

datestring = '1991-09-21'
foo = re.match('(\d{2})[/.-](\d{2})[/.-](\d{4})$', datestring)
print(foo)

ผลลัพธ์

21-09-1991
None