簡體   English   中英

我可以在python中使用re.sub時使用正則表達式命名組

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

我在嘗試使用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

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

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