Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用正则表达式在Python中搜索字符串中的重复单词?_Python_Regex - Fatal编程技术网

如何使用正则表达式在Python中搜索字符串中的重复单词?

如何使用正则表达式在Python中搜索字符串中的重复单词?,python,regex,Python,Regex,可以在Python中使用正则表达式搜索字符串中的重复单词吗 例如: string = ("Hello World hello mister rain") re.search(r'[\w ]+[\w ]+[\w ]+[\w ]+[\w ]', string) 我可以这样做吗?这样我就不必重复[\w]+[\w]。我不能只指定[\w]*5吗?我认为使用普通Python会更容易: from collections import Counter string = "Hello World hello

可以在Python中使用正则表达式搜索字符串中的重复单词吗

例如:

string = ("Hello World hello mister rain")

re.search(r'[\w ]+[\w ]+[\w ]+[\w ]+[\w ]', string)

我可以这样做吗?这样我就不必重复
[\w]+[\w]
。我不能只指定
[\w]*5
吗?

我认为使用普通Python会更容易:

from collections import Counter

string = "Hello World hello mister rain" # note: no () needed
words = string.split()

for word, count in Counter(map(str.lower, words)).iteritems():
    if count > 1:
        print "The word '{}' is repeated {} times.".format(word, count)

要匹配字符串中的第一个重复单词,可以使用:

re.match(r'.*(\b\w+\b).*\1', "hello World hello mister rain")
\b
匹配单词的边界

\1
与使用
()


抱歉,我不确定这是否是您想要的。

\w
是字母数字字符而不是单词,但是您可以使用
{5}
指定重复。我明白了,所以应该是:[\w]*{5}正确吗?此外,是否可以指定一个范围(3100)?相同的单词,或五个单独的单词?无论如何,你是如何定义一个单词的?我假设任何字母数字的东西,因为它是由空格分隔的。只有
[\w]+
才能匹配整个字符串,这就是你想要的吗?