Regex 多行、各种贪婪的正则表达式
给定以下文本,您将使用哪个PCRE正则表达式来提取以粗体标记的部分 00:20314 lorem ipsum want this kryptonite 00:02314 quux padding dont want this 00:03124 foo neither this 00:01324 foo but we want this stalagmite 00:02134 tralala not this 00:03124 bar foo and we want this kryptonite but not this(!) 00:02134 foo bar and not this either 00:01234 dolor sit amet EOF 00:20314 lorem ipsum 要这个吗 氪石 00:02314 quux 衬垫 我不要这个 00:03124福 也不是这个 00:01324福 但是我们想要这个 石笋 00:02134特拉拉拉 不是这个 00:03124巴富 我们想要这个 氪石,但不是这个(!) 00:02134福吧 这也不是 00:01234多洛·希特·阿梅特 EOF 注意,我们要提取以正则表达式开头,以“^0”结尾的部分(氪石石笋)Regex 多行、各种贪婪的正则表达式,regex,pcre,regex-greedy,Regex,Pcre,Regex Greedy,给定以下文本,您将使用哪个PCRE正则表达式来提取以粗体标记的部分 00:20314 lorem ipsum want this kryptonite 00:02314 quux padding dont want this 00:03124 foo neither this 00:01324 foo but we want this stalagmite 00:02134 tralala not this 00:03124 ba
我已经吃了一点,发现这是一个很难解决的问题。蒂亚 ^(00:.*(氪石|石笋))使用s修饰符一种方法是结合内联
(?sm)
这看起来很有效
# (?ms)^0(?:(?!(?:^0|kryptonite|stalagmite)).)*(kryptonite|stalagmite)
(?ms)
^ 0
(?:
(?!
(?: ^ 0 | kryptonite | stalagmite )
)
.
)*
( kryptonite | stalagmite )
我相信这将是最有效的:
^0(?:\R(?!\R)|.)*?\b(?:kryptonite|stalagmite)\b
显然,我们从
^0
开始,然后以kryptonite
或stallagmite
结束(在非捕获组中,为了方便起见),周围是
(?:\R(?!\R)|。)*?
是有趣的部分,所以让我们把它分解一下。第一个关键概念是PCRE
有几种方法可以做到这一点。分隔符可以在正文中吗?唯一的分隔符不需要正文中有其他的
^0
。相同的概念,但也包括关键字。Nice=)这个关键字可能不需要。你的更好。不过,一视同仁(+1)这是唯一的办法。你需要把$
添加到你的expression@HamZa,我不这么认为:00:03124巴富,我们想要这个氪石,但不是这个(!)
根本不符合预期的输出
^0(?:\R(?!\R)|.)*?\b(?:kryptonite|stalagmite)\b
(?: (?# start non-capturing group for repetition)
\R (?# match a newline character)
(?!\R) (?# not followed by another newline)
| (?# OR)
. (?# match any character, except newline)
)*? (?# lazily repeat this group)