正则表达式{{匹配

我需要匹配以下整个声明:

{{CalendarCustom|year={{{year|{{#time:Y}}}}}|month=08|float=right}} 

基本上每当有{需要有一个对应的} ,原始标记内有许多嵌入式{ } 。 例如{{match}}{{ma{{tch}}}}{{m{{a{{t}}c}}h}}

我现在有这个:

 (\{\{.+?(:?\}\}[^\{]+?\}\})) 

这不太奏效。

.NET正则表达式引擎允许递归匹配:

 result = Regex.Match(subject, @"\{ # opening { (?> # now match... [^{}]+ # any characters except braces | # or \{ (?) # a {, increasing the depth counter | # or \} (?<-DEPTH>) # a }, decreasing the depth counter )* # any number of times (?(DEPTH)(?!)) # until the depth counter is zero again \} # then match the closing }", RegexOptions.IgnorePatternWhitespace).Value; 

我建议为此编写一个简单的解析器/标记器。

基本上,你循环遍历所有字符并开始计算{}实例 – 递增{和递减} 。 记录每个第一个{以及每个最后一个的索引}的索引,您将获得嵌入式表达式的索引。

此时,您可以使用substring来获取这些并从原始字符串中删除/替换它们。

请参阅此问题以及为什么RegEx不适合的答案。