首页 > 解决方案 > 如何忽略lookbehind中的特定单词?

问题描述

完整字符串:

See Item 1A. Risk Factors – Regulatory, Compliance and Legal on page 13.
**Here Item 1A. Risk Factors – Regulatory, Compliance and Legal on page 13.**

我正在使用这段代码来获取句子**

(?i)(?<=\D|![see])Item.+?1A.+?Risk Factors(?=\D)(.+?)(?=Item 1B|$)

通过给出特定的词See来忽略它。

但它仍然采用两个句子。

标签: pythonregex

解决方案


如果你想在后面添加一个量词)(?<!\bSee\b.*),你可以使用PyPi regex 模块

(?<=\D)(?<!\bSee\b.*)Item.+?1A.+?Risk Factors(?=\D)(.+?)(?=Item 1B|$)

Python 演示

假设**那里表明句子之间的差异,您可以看到第二个是匹配的**,因为结尾是。

例如

import regex

pattern = r"(?i)(?<=\D)(?<!\bSee\b.*)Item.+?1A.+?Risk Factors(?=\D)(.+?)(?=Item 1B|$)"
test_str = ("See Item 1A. Risk Factors – Regulatory, Compliance and Legal on page 13.\n"
            "**Here Item 1A. Risk Factors – Regulatory, Compliance and Legal on page 13.**")
m = regex.search(pattern, test_str)
print(m.group())

输出

Item 1A. Risk Factors – Regulatory, Compliance and Legal on page 13.**

另一种选择可能是匹配您不想要的内容并使用交替捕获您想要保留的内容。

See匹配之前出现的整行,并使用模式在第 1 组Item中捕获,后向断言不是数字。

(?:^(?:(?!\bItem\b.)*)See\b.*|((?<=\D)Item.+?1A.+?Risk Factors(?=\D).+?(?=Item 1B|$)))

正则表达式演示


推荐阅读