首页 > 解决方案 > python正则表达式仅在括号中替换

问题描述

标签: pythonregex

解决方案


You may use the Group Reference here.

import re
before = '4ー3ー1ーー4ー31'
after  = re.sub(r'(\d+)ー(\d+)ー(\d+)', r'\1-\2-\3', before)
print(after)  # '4-3-1ーー4ー31'

Here, r'\1' is the reference to the first group, a.k.a, the first parentheses.


推荐阅读