简体   繁体   English

负前瞻正则表达式python

[英]negative lookahead regular expression python

I have a list of strings, I want to match a keyword if is not preceded by an "and". 我有一个字符串列表,如果前面没有“ and”,我想匹配一个关键字。 However, I would like to include the keyword if the "and" is preceded by another word. 但是,如果“和”后面有另一个单词,我想添加关键字。 Taking into account that the position of the "and" is not the same in all the strings. 考虑到“和”在所有字符串中的位置都不相同。

In my example below I would like to match strings that have the word "book", only if the word "book" is not after "and" unless the "and" is precede by a "tall" (the first and the third item in my list). 在下面的示例中,仅当单词“ book”不在“ and”之后时,我才想匹配具有“ book”一词的字符串,除非“ and”前面带有“ tall”(第一和第三项)在我的列表中)。 My attempt was using 我的尝试是使用

^((?!((?<!tall)\band\b)).)*book

but it is not working. 但它不起作用。 I'm not sure if I can include a negative look behind inside a negative lookahead 我不确定是否可以在否定前瞻的背后包含否定的眼神

  1. is a tall and wide book 是一本高大的书

  2. is a computer and a book of instructions 是一台计算机和一本说明书

  3. book with a pretty cover 封面精美的书

4.computer with nice headphones 4.带好耳机的电脑

I would phrase this using an alternation with both a positive and negative lookbehind: 我将使用正向和负向后面的交替表达这句话:

((?<!\band )|(?<=\btall and ))book

Demo 演示

The logic here is to match the word book if either of the following two conditions are true: 如果满足以下两个条件之一,则此处的逻辑是匹配单词book

  • book is not preceded by the word and at all book是不是在单词and所有
  • book is preceded by and , which in turn is also preceded by tall book的开头是and ,而后面又是tall

I didn't bother to include any Python code, but from what I gleaned in your question, the meat and potatoes is figuring out the regex, rather than the Python code. 我没有费心去包含任何Python代码,但是根据我在您的问题中所搜集到的内容,这些东西正在弄清楚正则表达式,而不是Python代码。

I figure out that my approach was not entirely wrong. 我发现我的方法并非完全错误。 It works when I take out the first boundary. 当我取出第一个边界时,它起作用。

^((?!((?<!tall) and\b)).)*book

I don't know yet why it doesn't work when I include that boundary. 我还不知道为什么在包含该边界时为什么它不起作用。 But it works. 但这有效。 Thank you 谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM