我正在尝试使用正则表达式平衡组来匹配嵌套标签,如下所示:
some text ...
{list}
nesting loop content
{list}
{list}
{list}
bala ...
{/list}
{/list}
{/list}
{/list}
end
我的表达:
\{(?<NAME>.+?)\}
[^\{\}]*
(
(
\{(?<NAME2>.+?)\}(?<OPEN>)
[^\{\}]*?
)
(
\{\/\<NAME2>\}(?<-OPEN>)
[^\{\}]*?
)
)*
(?(OPEN)(?!))
\{\/\<NAME>\}
我的问题:
only last 2 level pair can match.
最佳答案
通常,为了匹配嵌套标签,您需要类似于以下内容的内容:
(?>
\{(?<Open>\w+)\}
|
\{/(?<-Open>\<Open>)\}
|
(?(Open)[^{}]+)
)*
(?(Open)(?!))
这样您就可以匹配不同类型的嵌套标签,这看起来就像您想要做的那样。例如,它将匹配:
{list}
nesting loop content
{world}
{list}
{hello}
bala ...
{/hello}
{/list}
{/world}
{/list}
注释:
- 我使用的是
(?(Open)[^{}]+)
,因此我们仅匹配标签内的自由文本。 - 我对顶层和内部层使用相同的组。
你的非常接近。您基本上错过了中间组之间的一次交替:
(
\{(?<NAME2>.+?)\}(?<OPEN>)
[^\{\}]*?
)
| # <---- This
(
\{\/\<NAME2>\}(?<-OPEN>)
[^\{\}]*?
)
但是,您始终使用 $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")
另请参阅:
关于c# - 使用正则表达式平衡组来匹配嵌套标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43714112/