python - 使用 RegEx 查找无序单词

标签 python regex

我想使用 RegEx 查找字符串中出现一组单词的第一个序列(按任意顺序)。

例如,如果查找单词 hellomyworld,则:

  • 对于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/

相关文章:

html - beautifulsoup - 当文本前面有 img 标签时, anchor 标签的过滤文本不起作用

正则表达式:一次性获取没有扩展名的文件名?

Python - 属性错误 : 'OnDemand' object has no attribute 'calc'

Javascript 正则表达式寻找模式

python - 在实例 Django 模型保存方法中更新 FileField 值

Python 检查几个 if 条件(查找并用数字替换单词)

python - python中的正则表达式来捕获第一个运算符

regex - Ansible:在 GRUB 命令行中插入单词

python - 在 Seaborn 中绘制具有类似于 "hue"的多个属性的图形

python - 将python函数添加到c++程序