[英]A multi-line, variedly greedy, regular expression
鑒於以下文本,您將使用什么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
IOW,我們想用正則表達式提取以“^ 0”開頭並以“(kryptonite | stalagmite)”結尾的部分。
一直在咀嚼這一點,發現它很難破解。 TIA!
一種方法是將Negative Lookahead與內聯(?sm)
dotall和多行修飾符結合使用 。
(?sm)^0(?:(?!^0).)*?(?:kryptonite|stalagmite)
這看起來很有效。
# (?ms)^0(?:(?!(?:^0|kryptonite|stalagmite)).)*(kryptonite|stalagmite)
(?ms)
^ 0
(?:
(?!
(?: ^ 0 | kryptonite | stalagmite )
)
.
)*
( kryptonite | stalagmite )
我相信這將是最有效的:
^0(?:\R(?!\R)|.)*?\b(?:kryptonite|stalagmite)\b
顯然,我們從^0
開始,然后以kryptonite
或stalagmite
(在非捕獲組中,對於它來說)以\\b
字邊界包圍。
(?:\\R(?!\\R)|.)*?
雖然是有趣的部分,所以讓我們分解它。 一個關鍵概念首先是PCRE的\\R
換行序列 。
(?: (?# 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)
具有s修飾符的^(00:。*?(kryptonite | stalagmite))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.