Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use regex named group while using re.sub in python

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

like image 299
setu shwetank Avatar asked Oct 17 '25 20:10

setu shwetank


2 Answers

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'
like image 117
FlyingTeller Avatar answered Oct 20 '25 09:10

FlyingTeller


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))
like image 37
vks Avatar answered Oct 20 '25 09:10

vks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!