如何使用正则表达式在括号之间包含文本?

时间:2013-10-15 19:31:50

标签: c# regex

我当天的第二个问题!

我希望在c#中使用正则表达式在括号(开括号及其右括号)之间包含文本。 我用这个正则表达式:

@"\{\{(.*)\}\}

这是一个例子: 如果我的文字是:

text {{text{{anothertext}}text{{andanothertext}}text}} and text.

我想得到:

{{text{{anothertext}}text{{andanothertext}}text}}

但是这个正则表达式我得到了:

{{text{{anothertext}}

我知道另一个解决方案来获取我的文本但是有正则表达式的解决方案吗?

1 个答案:

答案 0 :(得分:2)

幸运的是,.NET的正则表达式引擎支持balancing group definitions形式的递归:

Regex regexObj = new Regex(
    @"\{\{            # Match {{
    (?>               # Then either match (possessively):
     (?:              #  the following group which matches
      (?!\{\{|\}\})   #  (but only if we're not at the start of {{ or }})
      .               #  any character
     )+               #  once or more
    |                 # or
     \{\{ (?<Depth>)  #  {{ (and increase the braces counter)
    |                 # or
     \}\} (?<-Depth>) #  }} (and decrease the braces counter).
    )*                # Repeat as needed.
    (?(Depth)(?!))    # Assert that the braces counter is at zero.
    \}}               # Then match a closing parenthesis.", 
    RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline);
相关问题