如何使用RegEx删除可能嵌套的括号?

时间:2014-07-06 00:02:43

标签: c# regex

我有以下文字:

  

{{some text {{with nested text}} and again}}以及其他一些文字{{remove this too}}

我希望匹配最后{{}}个括号,以便我留下:

  

还有更多文字在这里

这是我到目前为止所做的:

var text = Regex.Replace(content, "{{[^}}]*}}",string.Empty);

有什么想法吗?任何帮助将不胜感激。

更新添加一些可能有帮助的链接:

{{+}}? http://www.regexr.com/3941i

{{+}} http://www.regexr.com/3941f

3 个答案:

答案 0 :(得分:5)

var text = Regex.Replace(content, "{{.+}}", string.Empty);

编辑(平衡匹配)

string content = @"{{ some text {{ with nested text }} and again }} and some more text over here {{remove this too}}";

Regex re = new Regex(@" {{
    [^{}]*
    (
        (
            (?<Open>{{)
            [^{}]*
        )+
        (
            (?<Close-Open>}})
            [^{}]*
        )+
    )*
    (?(Open)(?!))
    }}", RegexOptions.IgnorePatternWhitespace);

var text = re.Replace(content, string.Empty);

有关详情:http://blogs.msdn.com/b/bclteam/archive/2005/03/15/396452.aspx

答案 1 :(得分:2)

你的正则表达式

{{[^}}]*}}

不起作用(try it),因为[^}}]不允许它超过第一个*关闭卷曲。如果你想捕捉“除最后两个之外的所有近卷曲”,那么你需要

\{\{.*\}\}[ ]+

Try it

我逃离了这些曲线是安全的。虽然它在regexstorm中没有它们,但它们是特殊字符,它们应该被转义。我还添加了尾随空格,只允许 捕获后期文本。

请注意,此正则表达式不会检查曲线是否平衡 - 它只是从前两个打开的曲线到最后两个盲目匹配。正则表达式不适合确定“平衡性”。

(*第一,因为[^}}]不正确。[^...]negative character class - 它匹配任何 一个 字符不在类中(方括号之间)。所以[^}}]相当于[^}}}}}}}}}}}}}}}]相当于[^}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}] }。)


请考虑将Stack Overflow Regular Expressions FAQ加入书签以供将来参考。

答案 2 :(得分:0)

我认为你不能一次性完成,这可以在php中工作,捕获匹配的{}然后修剪外部括号,重复

(\{(?:[^\{\}]*+|(?0))*\})

另外明智的我会将字符串标记,将其分解为{{,}}和文本并在php中处理结果(preg_match_all)

(\{\{)|(\}\})|([^{}]+)

并处理结果,

   Array
(
    [0] => Array
        (
            [0] => {{
            [1] =>  some text 
            [2] => {{
            [3] =>  with nested text 
            [4] => }}
            [5] =>  and again 
            [6] => }}
        )

    [1] => Array
        (
            [0] => {{
            [1] => 
            [2] => {{
            [3] => 
            [4] => 
            [5] => 
            [6] => 
        )

    [2] => Array
        (
            [0] => 
            [1] => 
            [2] => 
            [3] => 
            [4] => }}
            [5] => 
            [6] => }}
        )

    [3] => Array
        (
            [0] => 
            [1] =>  some text 
            [2] => 
            [3] =>  with nested text 
            [4] => 
            [5] =>  and again 
            [6] => 
        )

)

像 if(item == {{)++ nesting;等等,如果你遵循逻辑。