c# - 如何使用正则表达式获取包含在括号之间的文本?

标签 c# regex

今天的第二个问题!

我想在 C# 中使用正则表达式获取包含在括号(左括号及其右括号)之间的文本。 我使用这个正则表达式:

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

举个例子: 如果我的文字是:

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

我想得到:

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

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

{{text{{anothertext}}

我知道另一种获取文本的解决方案,但是否有使用正则表达式的解决方案?

最佳答案

幸运的是,.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);

关于c# - 如何使用正则表达式获取包含在括号之间的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19389495/

相关文章:

c# - 正确的单例类实现

c# - 为什么 Newtonsoft.JSON 在每个元素的每个属性中放置一个 '$' 标志?

c# - 从平面 XML 反序列化的嵌套类

asp.net - 字段不应超过 4 个字符且字符应唯一

javascript - HTML 标签的反向匹配

c# - 如何使用 C# 混合颜色 "naturally"?

c# - 从 C# 调用 C 函数,传递包含指针的结构

Python 正则表达式适用于 Regex101,但不适用于 Python 2

javascript - 当非 ASCII 字符具有 5 位以上的 Unicode 代码时,将其替换为其 Unicode 代码点

正则表达式替换中的 Python 转义字符串