2017-05-01 36 views
2

我試圖用正則表達式平衡組來匹配嵌套的標籤是這樣的:使用正則表達式平衡組來匹配嵌套的標籤

some text ... 
{list} 
    nesting loop content 
    {list} 
     {list} 
      {list} 
       bala ... 
      {/list} 
     {/list} 
    {/list} 

{/list} 
end 

我expresson:

\{(?<NAME>.+?)\} 
[^\{\}]* 
    (
     (
      \{(?<NAME2>.+?)\}(?<OPEN>) 
      [^\{\}]*? 
     ) 
     (
      \{\/\<NAME2>\}(?<-OPEN>) 
      [^\{\}]*? 
     ) 
    )* 
    (?(OPEN)(?!)) 
\{\/\<NAME>\} 

我的問題:

only last 2 level pair can match. 
+0

使用HTML/XML解析器。 –

回答

1

通常,要匹配嵌套標籤,您需要類似的東西:

(?> 
    \{(?<Open>\w+)\} 
    | 
    \{/(?<-Open>\<Open>)\} 
    | 
    (?(Open)[^{}]+) 
)* 
(?(Open)(?!)) 

Working example: Regex Storm

這種方式,您可以匹配嵌套不同類型的標籤,它看起來像你想要做什麼。例如,它會匹配這樣的:

{list} 
    nesting loop content 
    {world} 
     {list} 
      {hello} 
       bala ... 
      {/hello} 
     {/list} 
    {/world} 
{/list} 

注:

  • 我使用(?(Open)[^{}]+)所以我們只當它是標籤內匹配免費文本。
  • 我對頂層和內層使用相同的組。

此致相當接近。你基本上是缺失的中間羣體之間的一個交替:

(
    \{(?<NAME2>.+?)\}(?<OPEN>) 
    [^\{\}]*? 
) 
| # <---- This 
(
    \{\/\<NAME2>\}(?<-OPEN>) 
    [^\{\}]*? 
) 

Working example

但是,你總是使用最後一個值的$NAME2$NAME2是一個堆棧,但你永遠不會從它彈出值,只能推。這導致了一個錯誤:它也將匹配該字符串(這可能是錯誤的):

{list}    # Set $Name = "world" 
    nesting loop content 
    {world}    # Set $Name2 = "world" 
     {world}   # Set $Name2 = "world" 
      {hello}  # Set $Name2 = "hello" 
       bala ... 
      {/hello} # Match $Name2 ("hello") 
     {/hello}  # Match $Name2 ("hello") 
    {/hello}   # Match $Name2 ("hello") 
{/list}   # Match $Name ("list") 

參見:

相關問題