条件回顾(python正则表达式),如何排除某些词但包含某些词?

Conditional look-behind (python regex), how to exclude certain words but include certain words?

我在创建 python 正则表达式字符串以仅检索有效位置时遇到问题。

以下面的4行段落为例:

Enjoy up to 70% off at New York branches.

Enjoy up to 70% off in Canada.

Not valid at London branches.

Not valid in Germany.

我只想获取“纽约分支机构”和“加拿大”的文本,而没有获取“伦敦分支机构”和“德国”。

这行得通,但它获得了所有位置: ((?<=at ).*(?=\.))|((?<=in ).*(?=\.))

但是为什么这不起作用: ((?<!not )((?<=at ).*(?=\.))|((?<!not )((?<=in ).*(?=\.))

具体来说:我想要在单词 'at' 或 'in' 之后和句号之前的所有文本。但是,如果前面有 'not valid',我不想要它们。

我认为上面 hwnd 提供的答案是最好的方法

^(?!Not valid\b).*(?:at|in)(.*)\.$

但是为了回答你的问题,你想要完成的是这个

(?<=(?<!not valid )(?:at|in) ).*(?=\.)

Demo