簡體   English   中英

如何構造此正則表達式以查找以第一次出現的字符串結束的多行字符串?

[英]How construct this regex to find multiline string ended with first occurrence of a string?

我試圖匹配所有以"id="SomeDiv">並以"<!-- someComment"開頭的多行字符串。我的正則表達式無效,因為"<!-- someComment"多次出現,所以它匹配直到最后一次出現"<!-- someComment" 。我想只匹配第一次出現。

這與最后一次匹配

'/id="SomeDiv">.*\<\!-- someComment/sim'

我也嘗試了前瞻和后視(如下面的那個),但我做錯了,因為我什么都沒得到。

這與任何事情都不相符

'/id="SomeDiv">.*(?!\<\!-- someComment)<!-- someComment/sim'

我該如何正確匹配?

示例字符串

//The string to search in
$str = '<div id="SomeDiv>Some stuff in here<!-- someComment --> More stuff<!-- someComment -->';

//What I **should** find:
$expectedResult = 'id="SomeDiv>Some stuff in here<!-- someComment';

您可以使用Daniel Gimenez建議的惰性量詞,或者您可以使用此技巧:

$pattern = '~id="SomeDiv"[^>]*+>\K(?>[^<]++|<(?!!--))*~';

解釋:

\K                   # reset all that has been matched before
(?>                  # open an atomic group
    [^<]++           # all characters that are not <, one or more times
  |                  # OR
    <(?!!--)         # < not followed by !--
)*                   # close the group and repeat zero or more times

不需要捕獲組,因為結果是整個匹配。 請注意,由於未使用點,因此也不需要\\ s修飾符。

只需使用惰性量詞。 我添加了一個分組,以防你正在尋找的內容。

id="SomeDiv">(.*?)<!-- someComment

REY

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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