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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM