我想使用 RegEx 查找字符串中出现一组单词的第一个序列(按任意顺序)。
例如,如果查找单词 hello
、my
和 world
,则:
- 对于
hello my sweet world
,表达式将匹配hello my sweet world
; - 对于
oh my, hello world
它将匹配my, hello world
; - 对于
oh my world, hello world
它将匹配my world, hello
; - 对于
hello world
,将没有匹配项。
经过一番研究,我尝试了表达式 (?=.*?\bhello\b)(?=.*?\bmy\b)(?=.*?\bworld\b).*
,这不能解决我的问题,因为如果所有单词都存在,它会匹配整个字符串,如下所示:
- 对于
oh my world, hello world
它匹配oh my world, hello world
实现我所描述的内容的适当表达方式是什么?
(虽然 RegEx 是我的程序的首选方法,但如果您认为这不是可行的方法,欢迎使用任何其他 python 解决方案。)
最佳答案
使用Pattern.finditer()的统一迭代pythonic方法功能和Set对象:
import re
test_str = '''The introduction here for our novel.
Oh, hello my friend. This world is full of beauty and mystery, let's say hello to universe ...'''
words_set = {'my', 'hello', 'world'} # a set of search words
words_set_copy = set(words_set)
pat = re.compile(r'\b(my|hello|world)\b', re.I)
start_pos = None
first_sequence = ''
for m in pat.finditer(test_str):
if start_pos is None:
start_pos = m.start() # start position of the 1st match object
words_set_copy.discard(m.group()) # discard found unique match
if not words_set_copy: # all the search words found
first_sequence += test_str[start_pos: m.end()]
break
print(first_sequence)
输出:
hello my friend. This world
<小时/>
您可以将上述方法转化为一个函数,使其可重用。
关于python - 使用 RegEx 查找无序单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53899291/