在我的项目中,我需要能够将字符串中的正则表达式替换为另一个正则表达式。
例如,如果我有两个正则表达式[a-c]
和[x-z]
;abc";用";xyz";,或者字符串";你好,阿丹;用";你好xdxn";。我该怎么做?
我们构建一个映射,然后逐字母翻译。当使用get for dictionary时,第二个参数指定如果找不到要返回的内容。
>>> trans = dict(zip(list("xyz"),list("abc")))
>>> trans
{'x': 'a', 'y': 'b', 'z': 'c'}
>>> "".join([trans.get(i,i) for i in "hello xdxn"])
'hello adan'
>>>
或者将trans中的顺序更改为其他方向
>>> trans = dict(zip(list("abc"),list("xyz")))
>>> trans
{'a': 'x', 'b': 'y', 'c': 'z'}
>>> "".join([trans.get(i,i) for i in "hello adan"])
'hello xdxn'
>>>
尝试使用re.sub
>>>replace = re.sub(r'[a-c]+', 'x','Hello adan')
>>>replace
'Hello xdxn'
>>>re.sub(r'[a-c]+', 'x','Hello bob')
'Hello xox'