匹配平衡括号的正则表达式 [英] Regular expression to match balanced parentheses

查看:55
本文介绍了匹配平衡括号的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个正则表达式来选择两个外括号之间的所有文本.

I need a regular expression to select all the text between two outer brackets.

示例:some text(text here(possible text)text(possible text(more text)))end text

结果:(text here(possible text)text(possible text(more text)))

推荐答案

正则表达式是错误的工作工具,因为您正在处理嵌套结构,即递归.

Regular expressions are the wrong tool for the job because you are dealing with nested structures, i.e. recursion.

但是有一个简单的算法可以做到这一点,我对此进行了更详细的描述在这个答案中上一个问题.要点是编写代码,扫描字符串,保留尚未与右括号匹配的左括号的计数器.当该计数器归零时,您就知道已到达最后一个右括号.

But there is a simple algorithm to do this, which I described in more detail in this answer to a previous question. The gist is to write code which scans through the string keeping a counter of the open parentheses which have not yet been matched by a closing parenthesis. When that counter returns to zero, then you know you've reached the final closing parenthesis.

这篇关于匹配平衡括号的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆