简体   繁体   中英

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

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))

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM