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

时间:2018-03-21 06:10:30

标签: python regex python-3.x

我正在尝试使用re.sub时使用群组。以下工作正常。

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

输出

  

2026年2月12日

我的查询不是使用组号,而是可以使用组名作为:         \ day- \月 - \年

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:2)

使用\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'