编写一个程序,匹配字符串中的形如AABBCC的子串,并将其替换为ABC.,如对于原始字符串s="hello, big big red red hat hat you know small small green green cat cat"被替换后得到的字符串为"hello, big red hat you know small green cat"、
上课这么教的,但是是错的
s="hello, big big red red hat hat you know small small green green cat cat"
import re
re.sub(r'(\b\w+)\1',r'\1',s)
s="hello, big big red red hat hat you know small small green green cat cat"
import re
new_s = re.sub(r'(\b\w+)(\s+\1)', r'\1', s)
print(new_s)
不知道你们怎么教的,但这样写是可以的
import re
x = "this is is a desk"
pattern = re.compile(r'\b(\w+)(\s+\1){1,}\b')
matchResult = pattern.search(x)
x = pattern.sub(matchResult.group(1), x)
print(x)