set*_*ank 3 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))
Run Code Online (Sandbox Code Playgroud)
输出是
02-12-2026
我的查询不是使用组号,我们可以使用组名作为:\day-\month-\year
访问组有一个非常直接的语法,使用 \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'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
456 次 |
| 最近记录: |