使用regex替换字符串

2024-09-30 00:34:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我用python写了这个字符串

a = "haha" 
result = "hh"

我想要实现的是使用regex替换所有出现的“aha”到“h”、所有出现的“oho”到“h”、所有出现的“ehe”到“h”

“h”只是一个例子。基本上,我想保留中心人物。换言之,如果它是'eae',我想把它改成'a'

我的正则表达式就是这个

"aha|oho|ehe"

我想过这么做

import re
reg = re.compile('aha|oho|ehe')

然而,我被困在如何实现这种替代而不使用循环迭代所有可能的组合?你知道吗


Tags: 字符串importrehhresultreg中心例子
2条回答

您可以使用^{}

import re

print re.sub('aha|oho|ehe', 'h', 'haha')  # hh
print re.sub('aha|oho|ehe', 'h', 'hoho')  # hh
print re.sub('aha|oho|ehe', 'h', 'hehe')  # hh
print re.sub('aha|oho|ehe', 'h', 'hehehahoho')  # hhhahh

re.sub(r'[aeo]h[aeo]','h',a)呢?你知道吗

相关问题 更多 >

    热门问题