查找一个没有其他单词开头的单词

时间:2020-09-24 19:14:17

标签: python regex

我想知道如何编写一个正则表达式模式来查找字符串,其中列表中的任何单词都不会以另一个单词开头:

要给出上下文,请想象两个单词列表:

Parts = ['spout', 'handle', 'base']
Objects = ['jar', 'bottle']

想象以下字符串

string = 'Jar with spout and base'
string2 = 'spout of jar'
string3 = 'handle of jar'
string4 = 'base of bottle with one handle' 
string5 = 'bottle base'

我想编写一条规则,以便如果我们有一个表达式,例如“罐嘴”,“瓶柄”或“瓶底”,我可以输出一条语句,例如“对象是罐子的碎片,有部分罐嘴” / base”添加到数据帧中,但是如果我们有一个类似“ jar with spout”的表达式,我可以输出一个类似“ object is jug,has part spout”的表达式。

基本上,我想编写一条规则,以便如果字符串中的任何单词都在字符串中,则我们写该对象是一个片段-除非单词以'with'开头。

所以我写了这个,后面是负号,后面是。*,后面是单词中的任何单词:

rf"(?!with)(.*)(?:{'|'.join(Part)})"

但是这似乎不起作用:当我在Python中尝试时,“带有喷口的罐子”仍会匹配此模式。

所以我不确定如何编写正则表达式模式以排除任何涉及“ with”的表达式,后跟任何字符序列,然后在“ Parts”中输入单词

非常感谢您在这里可以提供的任何帮助!

1 个答案:

答案 0 :(得分:1)

您可以轻松地为PyPi regex库(与pip install regex一起安装)编写这种模式:

(?<!\bwith\b.*?)\b(?:spout|handle|base)\b

请参见regex demo详细信息

  • (?<!\bwith\b.*?)-在当前位置的左侧,应该没有完整的单词with,除了换行符以外,其他任何零个或多个字符都应尽可能少
  • \b(?:spout|handle|base)\b-整个单词spouthandlebase

请参见Python demo

import regex
Parts = ['spout', 'handle', 'base']
Objects = ['jar', 'bottle']
strings = ['Jar with spout and base','spout of jar','handle of jar','base of bottle with one handle','bottle base']
pattern = regex.compile(rf"(?<!\bwith\b.*?)\b(?:{'|'.join(Parts)})\b")
print( list(filter(pattern.search, strings)) )
# => ['spout of jar', 'handle of jar', 'base of bottle with one handle', 'bottle base']
相关问题