简体   繁体   中英

string substitution using regex

I have this string in python

a = "haha" 
result = "hh"

What i would like to achieve is using regex to replace all occurrences of "aha" to "h" and all "oho" to "h" and all "ehe" to "h"

"h" is just an example. Basically, i would like to retain the centre character. In other words, if its 'eae' i would like it to be changed to 'a'

My regex would be this

"aha|oho|ehe"

I thought of doing this

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

However, i am stuck on how to achieve this kind of substitution without using loops to iterate through all the possible combinations?

You can use re.sub :

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)呢?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM