带有惰性量词的环顾四周
Lookarounds with lazy quantifiers
我正在尝试在正则表达式中使用 lookbehind,然后使用惰性“匹配所有模式”(.+?)
,但我想知道我是否可以通过这种方式使用 lookarounds。
例如,我有以下正则表达式:(?<!learn).+?write a regex
"I'm learning how to write a regex"
(应该不匹配)
"I know how to write a regex"
(应该匹配)
"I know how to read an write a regex"
(应该匹配)
"I want to know how to write a regex"
(应该匹配)
"I want to learn how to write a regex"
(应该不匹配)
如果你使用上面的正则表达式,你会得到匹配的所有内容。
您的模式匹配所有行,因为 (?<!learn).+?write a regex
将 运行 在第一个位置向后看,断言当前位置左侧的内容不是 learn
断言为真,这部分将立即匹配,直到第一次出现 write a regex
你可以做的是利用 PyPi regex module 支持后视的无限量词:
(?<!\blearn.+?)\bwrite a regex\b
import regex
pattern = r"(?<!\blearn.+?)\bwrite a regex\b"
strings = [
"I'm learning how to write a regex",
"I know how to write a regex",
"I know how to read an write a regex",
"I want to know how to write a regex",
"I want to learn how to write a regex"
]
for s in strings:
if regex.search(pattern, s):
print(s)
输出
I know how to write a regex
I know how to read an write a regex
I want to know how to write a regex
我正在尝试在正则表达式中使用 lookbehind,然后使用惰性“匹配所有模式”(.+?)
,但我想知道我是否可以通过这种方式使用 lookarounds。
例如,我有以下正则表达式:(?<!learn).+?write a regex
"I'm learning how to write a regex"
(应该不匹配)"I know how to write a regex"
(应该匹配)"I know how to read an write a regex"
(应该匹配)"I want to know how to write a regex"
(应该匹配)"I want to learn how to write a regex"
(应该不匹配)
如果你使用上面的正则表达式,你会得到匹配的所有内容。
您的模式匹配所有行,因为 (?<!learn).+?write a regex
将 运行 在第一个位置向后看,断言当前位置左侧的内容不是 learn
断言为真,这部分将立即匹配,直到第一次出现 write a regex
你可以做的是利用 PyPi regex module 支持后视的无限量词:
(?<!\blearn.+?)\bwrite a regex\b
import regex
pattern = r"(?<!\blearn.+?)\bwrite a regex\b"
strings = [
"I'm learning how to write a regex",
"I know how to write a regex",
"I know how to read an write a regex",
"I want to know how to write a regex",
"I want to learn how to write a regex"
]
for s in strings:
if regex.search(pattern, s):
print(s)
输出
I know how to write a regex
I know how to read an write a regex
I want to know how to write a regex