簡體   English   中英

多線,多變貪婪,正規表達

[英]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開始,然后以kryptonitestalagmite (在非捕獲組中,對於它來說)以\\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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM