【python】正則替換


正則替換可以使用函數

例如:替換字符串中所有#1.2.3.4#格式中的數字為0

import re

def replace(x):
    def _replace(matched):
        m = matched.group()
        change = re.sub("\d", '0', m)
        return change

    pattern = "#((\d*\.)+\d+)#"
    r = re.sub(pattern, _replace, x)
    return r

x = "ab.c.d.#1.0.3.4# 2.2.2asdf"
r = replace(x)

print x
print r

輸出:

ab.c.d.#1.0.3.4# 2.2.2asdf
ab.c.d.#0.0.0.0# 2.2.2asdf


免責聲明!

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



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