python re.sub 括号匹配替换匹配到的内容后接数字

时间:2021-12-24 22:37:49

python re.sub 括号匹配替换匹配到的内容后接数字

如果代码为:

text = re.sub(r'(?<=[{])([a-z]+)6(?=[}])', r'\13', text)

上面代码会报错,因为没有组合13,所以不能获得组合13的内容。

但是我们要实现的是将{ni6}中的ni6替换成ni3,我们应该这么写:

text = re.sub(r'(?<=[{])([a-z]+)6(?=[}])', r'\g<1>3', text)

 

另外,记录我的批量替换代码(将文件夹下的所有文件的拼音6都替换成3):

# -*- coding: utf-8 -*-

import os
import glob
import shutil
import re

here = os.path.dirname(os.path.abspath(__file__))

for path in glob.glob(os.path.join(here, '**', '*'), recursive=True):
    if path.endswith('.py') or not os.path.isfile(path):
        continue
    print(path)
    dst_path = path + '.jacen_bak'
    os.rename(path, dst_path)
    # shutil.copy2(path, dst_path)
    try:
        with open(dst_path, 'r', encoding='utf-8') as f:
            text = f.read()
        text = re.sub(r'(?<=[{])([a-z]+)6(?=[}])', r'\g<1>3', text)
        with open(path, 'w', encoding='utf-8') as f:
            f.write(text)
        os.remove(dst_path)
    except UnicodeDecodeError as e:
        os.rename(dst_path, path)
        print(e, path)