I am trying to use groups while using re.sub
. The below works fine.
dt1 = "2026-12-02"
pattern = re.compile(r'(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})')
m = pattern.match(dt1)
print(m.group('year'))
print(m.group('month'))
print(m.group('day'))
repl = '\\3-\\2-\\1'
print(re.sub(pattern, repl, dt1))
Output is
02-12-2026
My query is instead of using group numbers can we use group names as: \day-\month-\year
There is a pretty straight up syntax for accesing groups, using \g<group name>
import re
dt1 = "2026-12-02"
pattern = re.compile(r'(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})')
print(pattern.sub(r"\g<day>-\g<month>-\g<year>", dt1))
Output: '02-12-2026'
dt1 = "2026-12-02"
from datetime import datetime
print datetime.strptime(dt1, "%Y-%m-%d").strftime("%d-%m-%Y")
There is no need for regex here.
Output:
02-12-2026
But if you want to use regex then here it goes,
dt1 = "2026-12-02"
pattern = re.compile(r'(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})')
m = pattern.match(dt1)
def repl(matchobj):
print matchobj.groupdict()
return matchobj.group('year')+"-"+matchobj.group('month')+"-"+matchobj.group('day')
print(re.sub(pattern, repl, dt1))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With