Python replace 函数增加正则支持

2020-08-12  本文已影响0人  茄子_0937

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*}','"}')
上一篇下一篇

猜你喜欢

热点阅读