在这种情况下,使用正则表达式 (PCRE) 并不是最佳选择,因为您需要重新解析每个嵌套级别的内部内容(使用适当解析器的原因之一会更好)。
也就是说,可以使用以下模式来完成:
~
{if:\s*+
(?<condition>
[^{}]++
)
}
(?<then>
(?:
(?:(?!{if:[^{}]++}|{else}|{/endif}).)*+
(?R)*+
)*+
)
(?:
{else}
(?<else>
(?:
(?:(?!{if:[^{}]++}|{else}|{/endif}).)*+
(?R)*+
)*+
)
)?+
{/endif}
~six
Perl 示例@ideone。
在这个文本上
if: "'x' == 'y'"}
a
{else}
b
{/endif}
{if: "'x' == 'y'"}
c
{/endif}
{if:minimal}{else}{/endif}
{if: "'nested' == 'things'"}
{if: "'x' == 'y'"}x{if:minimal}{else}{/endif}x{/endif}
{else}
b{if: "'x' == 'y'"}c{/endif}{if: "'x' == 'y'"}c{/endif}
{/endif}
{if:foo} unbalanced {if:bar}ignores first if{/endif}
它匹配
*** matched if:
* cond: "'x' == 'y'"
* then:
a
* else:
b
*** matched if:
* cond: "'x' == 'y'"
* then:
c
*** matched if:
* cond: minimal
* then:
* else:
*** matched if:
* cond: "'nested' == 'things'"
* then:
{if: "'x' == 'y'"}x{if:minimal}{else}{/endif}x{/endif}
* else:
b{if: "'x' == 'y'"}c{/endif}{if: "'x' == 'y'"}c{/endif}
*** matched if:
* cond: bar
* then: ignores first if