Python replace 函数增加正则支持

Python 的 replace 方法没有正则功能,所以对字符串的替换有局限。 re 模块的 re.sub  可以利用正则进行字符替换,但是使用比较麻烦,字符串多次替换显得笨拙。所以我,利用re.sub 的正则功能,对字符串的replace方法进行了改造。

import re

class string(str):
    def replace(self,regex,cls):
        self = re.sub(regex,cls,self)
        this = string(self)
        return this

a = '{ name : abc}'
b = string(a)
b.replace('{\s*','{"').replace('\s*:\s*','":"').replace('\s*}','"}')
posted @ 2020-07-29 16:41  lvws  阅读(8)  评论(0)    收藏  举报