2013-10-15 96 views
3

我今天的第二个问题!如何使用正则表达式在括号内包含文本?

我想在c#中使用正则表达式在括号(左括号和右括号)之间包含文本。 我用这个表达式:

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

下面的例子: 如果我的文字是:

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

我想:

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

但这个表达式我得到:

{{text{{anothertext}} 

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

+3

这些你可能不想与正则表达式来尝试各种各样的东西,而是一个解析器和状态机。 –

+0

[Here's](http://stackoverflow.com/questions/546433/regular-expression-to-match-outer-brackets)与@KevinDiTraglia给出的类似问题的答案 – Jonesopolis

+0

@KevinDiTraglia:.NET的正则表达式引擎*有*一台状态机。 –

回答

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); 
相关问题