Regular expression back-references in Python

It's simple (assuming you know about regular expressions). Here is how. Say you have a string s containing a date of the format MM/DD/YYYY that you want to change into YYYY-MM-DD. You first compile your regular expression using re.compile, define your string s and use re.sub to replace the content of the string.

>>> import re
>>> pat=re.compile(r’^(0?[1-9]|1[0-2])/(0?[1-9]|[12][0-9]|3[01])/(\d\d\d?\d?)$’)
>>> s = ‘12/31/2021’
>>> re.sub(pat, r’\3-\1-\2′, s)

And that's it. Hope this is useful.


Popular Posts