Products
GG网络技术分享 2025-03-18 16:14 32
编写一个程序,匹配字符串中的形如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)
一. python正则表达式介绍
正则表达式是一个特殊的字符序列,它能帮助你方便的检查一个字符串是否与某种模式匹配。
Python 自1.5版本起增加了re 模块,它提供 Perl 风格的正则表达式模式。
re 模块使 Python 语言拥有全部的正则表达式功能。
compile 函数根据一个模式字符串和可选的标志参数生成一个正则表达式对象。该对象拥有一系列方法用于正则表达式匹配和替换。
re 模块也提供了与这些方法功能完全一致的函数,这些函数使用一个模式字符串做为它们的第一个参数。
二. re模块
2.1 match方法
Demand feedback