简体   繁体   English

我可以在python中使用re.sub时使用正则表达式命名组

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

I am trying to use groups while using re.sub . 我在尝试使用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 2026年2月12日

My query is instead of using group numbers can we use group names as: \\day-\\month-\\year 我的查询不是使用组号,而是使用组名称:\\ 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> 使用\\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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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