c# - 使用正则表达式平衡组来匹配嵌套标签

标签 c# regex balancing-groups

我正在尝试使用正则表达式平衡组来匹配嵌套标签,如下所示:

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)(?!))

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")

另请参阅:

关于c# - 使用正则表达式平衡组来匹配嵌套标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43714112/

相关文章:

c# - 使用对象查询 Entity Framework

c# - Json.NET,如何自定义序列化以插入 JSON 属性

c# - 如何在 json 序列化中跳过属性名称?

javascript - 如何验证手机号码的输入字段

c# 正则表达式与平衡组没有响应

c# - GC 不收集实现互操作程序集接口(interface)的对象,没有根

regex - 使用 Regex 识别文件名中两个不同子字符串中的任何一个?

python - 使用 QCompleter 全局输入?

c# - 正则表达式平衡组