如何使用RegEx删除可能嵌套的括号?
我有以下文字:
{{some text {{with nested text}} and again}}以及其他一些文字{{remove this too}}
我想匹配OUTERmost {{}}括号,以便我留下:
还有一些文字在这里
这是我到目前为止:
var text = Regex.Replace(content, "{{[^}}]*}}",string.Empty);
有任何想法吗? 任何帮助将非常感激。
更新添加一些可能有用的链接:
{{。+?}} http://www.regexr.com/3941i
{{。+}} http://www.regexr.com/3941f
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)(?!)) }}", RegexOptions.IgnorePatternWhitespace); var text = re.Replace(content, string.Empty);
有关详细信息,请访问: http : //blogs.msdn.com/b/bclteam/archive/2005/03/15/396452.aspx
你的正则表达式
{{[^}}]*}}
不起作用( 尝试 ),因为[^}}]
不允许它超过第一个* closecurl。 如果你想捕捉“除最后两个之外的所有近curl”,那么你需要
\{\{.*\}\}[ ]+
试试吧
为了安全起见我逃离了。 虽然它在regexstorm中没有它们,但它们是特殊字符,它们应该被转义。 我还添加了尾随空格, 只能按照您的意愿捕获后置文本。
请注意,这个正则表达式不会检查曲线是否平衡 – 它只是从前两个打开的曲线到最后两个盲目匹配。 正则表达式不适合确定“平衡性”。
(*第一个,因为[^}}]
不正确。 [^...]
是一个负字符类 – 匹配任何 一个不在类中的字符 (在方括号之间)。所以[^}}]
相当于[^}}}}}}}}}}}}}}}]
等同于[^}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}]
请考虑将Stack Overflow Regular Expressions FAQ添加为书签,以备将来参考。
我认为你不能一次性完成它,这可以在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; 等等,如果你遵循逻辑。