【问题标题】:Can I use regex named group while using re.sub in python我可以在 python 中使用 re.sub 时使用正则表达式命名组吗
【发布时间】:2018-03-21 06:10:30
【问题描述】:

我在使用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-\month-\year

【问题讨论】:

    标签: python regex python-3.x


    【解决方案1】:

    使用\g&lt;group name&gt; 访问组有一个非常直接的语法

    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'
    

    【讨论】:

    • 太棒了。这就是我一直在寻找的。谢谢@FlyingTeller
    【解决方案2】:
    dt1 = "2026-12-02"
    from datetime import datetime
    print datetime.strptime(dt1, "%Y-%m-%d").strftime("%d-%m-%Y")
    

    这里不需要正则表达式。

    输出:

    02-12-2026

    但是如果你想使用正则表达式,那么就可以了,

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

    【讨论】:

    • 嗨,我正在尝试使用 re.sub() 和命名组来实现相同的目的。
    • @setushwetank,你为什么不想使用datetime 模块?
    猜你喜欢
    • 2010-09-29
    • 2013-05-23
    • 1970-01-01
    • 1970-01-01
    • 2010-09-22
    • 1970-01-01
    • 2011-02-06
    • 2021-06-20
    • 1970-01-01
    相关资源
    最近更新 更多