Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.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_Findall - Fatal编程技术网

Python正则表达式查找与其他单词分隔的单词

Python正则表达式查找与其他单词分隔的单词,python,regex,findall,Python,Regex,Findall,有没有一种方法可以使用re.findall或另一种正则表达式方法来计算按指定顺序出现的单词数,并用任意数量的单词分隔 下面是一个“暴力”实现: def search_query(query, page): count=i=0 for word in page.split(): if word == query[i]: i+=1 if i==len(query): count+=1

有没有一种方法可以使用
re.findall
或另一种正则表达式方法来计算按指定顺序出现的单词数,并用任意数量的单词分隔

下面是一个“暴力”实现:

def search_query(query, page):
    count=i=0
    for word in page.split():
            if word == query[i]: i+=1
            if i==len(query): 
                count+=1
                break
    print count

search_query(['hello','kilojoules'],'hello my good friend kilojoules')
1
例如,当查询为
hello kilojoules
时,我想将
hello my good friend kilojoules
识别为我查询的一个实例,但对于
kilojoules是我的好朋友,不计算在内


下面是我对一个令人满意的正则表达式的天真尝试:
re.findall('hello\s\Skilojoules','hello my friend kilojoules')
。这不管用。我认为这会起作用,因为我对这句话的理解是“找到所有用空格或空格分隔的
hello
kilojoules
的实例”

我在
re.findall('hello.*?kilojoules','a happy hello my amigo kilojoules now bye')中找到了成功的答案。
,按照斯特里比雪夫的建议

让我澄清一下:

(?s)\bhello\b.*?\bkilojoules\b
这个正则表达式的意思是*匹配一个完整的单词hello,然后匹配任何字符,甚至是一个空格和换行符,然后匹配一个完整的单词千焦耳

如果没有换行符,并且不关心整个单词匹配,请使用

hello.*?kilojoules
请注意,
\s\s
只是一个空格,后跟一个非空格。因此,
hello\s\skillojoules
可以匹配
hello-bkilojoules
,但不能匹配
hello-kilojoules

可能是
(?s)\bhello\b.?\bkilojoules\b
?请注意,
\s\s
只是一个空格,后跟一个非空格
hello\s\skillojoules
可以匹配
hello bkilojoules
,但不能匹配
hello kilojoules
。除非您出于任何原因喜欢键入反斜杠按钮,否则在此处使用的通用语句,@stribizev
re.findall(“(?s)\bhello\b.\bkilojoules\b”,“hello my amigo kilojoules”)
不会返回任何内容