Python中可以使用正则表达式(regex)来查找重复字符串。正则表达式是一种强大的模式匹配工具,可以用来在文本中查找、替换和提取特定的字符串。
要使用正则表达式查找重复字符串,可以使用re模块中的findall()函数。findall()函数可以返回所有匹配的字符串,并以列表的形式返回结果。
下面是一个示例代码,演示如何使用正则表达式查找重复字符串:
import re
def find_duplicates(text):
pattern = r'(\b\w+\b)\s+\b\1\b'
duplicates = re.findall(pattern, text)
return duplicates
text = "This is a test test string with duplicate duplicate words."
duplicates = find_duplicates(text)
print(duplicates)
输出结果为:
['test', 'duplicate']
在上面的示例中,我们定义了一个正则表达式模式(\b\w+\b)\s+\b\1\b
,其中\b\w+\b
表示匹配一个单词,\s+
表示匹配一个或多个空格,\b\1\b
表示匹配前面匹配到的单词。通过使用re.findall()
函数,我们可以找到所有重复的单词。
领取专属 10元无门槛券
手把手带您无忧上云