[英]RegEx: nested tags
我使用regexp,但是我無法解決這個問題。 我創建了自己的引擎,如DLE。 我有[a],[/ a],[b],[/ b]等標簽。我使用regexp
'\\[a\\](.*?)\\[/a\\]'si
或喜歡
'\\[a\\](.*?)(\\[/a\\])+'si
我想怎么都行不通 我需要收到:
from '[a]delete[/a]' : ''
from '[a][b]delete[/b][/a]' : '',
from '[a][a]delete[/a][/a]' : '', with '\\[a\\](.*?)\\[/a\\]'si it returns '[/a]'
from '[b][a]delete[/a][b]' : '[b][/b]'
from '[b][a]delete[/a][b] [a]delete[/a]' : '[b][/b]'
from '[a]
delete
[a]
[b]delete[/b]
[/a]
delete
[/a]
[b]
[a]delete[/a]
nodelete
[/b]'
:
'[b]
nodelete
[/b]'
幫助我創建正確的正則表達式!
PHP方式
您可以使用php一口氣做到這一點。 但是要處理嵌套標簽,您需要使用遞歸功能,因此您無法對Javascript執行相同的操作:
$text = preg_replace('~\s*\[a](?:[^[]+|\[(?!/?a])|(?R))*+\[/a]\s*~', '', $text);
圖案細節
~ # pattern delimiter
\s* # only here to remove leading whitespaces
\[a]
(?: # non-capturing group: describes the allowed
# content between tags:
[^[]+ # - all that is not a [
| # OR
\[ (?!/?a]) # - a [ that is not the begining of an opening
# or closing "a" tag
| # OR
(?R) # - recurse to the whole pattern
)*+ # repeat the group zero or more times (possessive quantifier)
\[/a]
\s* # to remove trailing spaces
~
JavaScript方式
由於遞歸功能不適用於ECMAScript regex引擎,因此解決此問題的方法是使用針對最里面的“ a”標簽的多次替換。 要完成此任務,您可以使用以下模式,該模式禁止嵌套的“ a”標簽(請注意,該模式與以前的模式非常相似,語法(?=(subpattern*))\\1
僅模擬所有格修飾符) :
text = text.replace(/\s*\[a\](?=((?:[^\[]+|\[(?!\/?a\]))*))\1\[\/a\]\s*/g, '');
您需要應用此替換,直到沒有更多標簽可以替換為止。 您可以使用閉包作為替換來增加計數器的數量,從而檢測替換的數量,然后將所有內容放入do...while
循環中。 例:
var counter;
do {
counter = 0;
text = text.replace(/\s*\[a\](?=((?:[^\[]+|\[(?!\/?a\]))*))\1\[\/a\]\s*/g, function (m) {counter++; return '';});
} while (counter>0)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.