【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