簡體   English   中英

正則表達式:里面有一個正則表達式

[英]Regex: there's a regex inside

我正在深入正則表達式的陰暗面。 我需要解析這個:

{{word(a|b|c)|word$1}}
{{word(s?)|word$1}}
{{w(a|b|c)ord(s?)|w$1ord$2}}

您可能已經注意到,它是一個搜索和替換方案,其中包含正則表達式。 Wikimedia引擎做得很好,但是我找不到它的作用: 就在這里

我只需要將第一部分和第二部分分成兩個單獨的變量即可。 例如:

preg_match(REGEX, "{{word(a|b|c)|word$1}}", $result) // Applying REGEX on this
echo $result[1] // word(a|b|c)
echo $result[2] // word$1

你會怎么做? 就像正則表達式中的正則表達式,我完全迷失了...

您可以使用以下內容匹配零件:

{{((?:(?!}}).)+)\|([^|]+?)}}

請注意,如果您允許任意PCRE正則表達式,那么可以構建一些非常復雜和緩慢的模式,可能允許在您的站點上進行簡單的DoS攻擊。

這實際上取決於嵌套的深度,但是您可以將其拆分為| ,小心不要分開任何| 在括號內。 我想這是簡單的方法:

$str = 'word(a|b|c)|word$1'; // Trim off the leading and trailing {{ and }}
$items = explode('|', $str);
$realItems = array();

for($i = 0; $i < count($items); $i++) {
    $realItem = $items[$i];
    while(substr_count($realItem, '(') > substr_count($realItem, ')')) {
        // Glue them together and skip one!
        $realItem .= '|' . $items[++$i];
    }

    $realItems[] = $realItem;
}

現在$realItems[]包含2-4個鍵值,您可以將它們簡單地傳遞到preg_replace ; 它會為你做所有的工作。

實際上並不難。

問題是,替換字符串將只包含一個逃脫| ,即\\|

對於其中一個場合, .*實際上在這里很有用。

執行: preg_match("^{{(.*)\\|([^|]+(?:\\\\\\|[^|]*)*)}}$", $result); ,這應該做您想要的。

這里的訣竅是第二組:它是normal* (special normal*)*模式,其中normal[^|] (除了管道之外的任何東西),而special\\\\\\| (反斜杠后跟管道)。

暫無
暫無

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

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