如何编写与嵌套括号匹配的递归正则表达式? [英] How to write a recursive regex that matches nested parentheses?
问题描述
我正在尝试编写一个与嵌套括号匹配的正则表达式,例如:
I am trying to write a regexp which matches nested parentheses, e.g.:
"(((text(text))))(text()()text)(casual(characters(#$%^^&&#^%#@!&**&#^*!@#^**_)))"
这样的字符串应该匹配,导致所有嵌套括号都被关闭,
A string like this should be matched, cause all the nested parentheses are closed, instead:
"(((text)))(text)(casualChars*#(!&#*(!))"
应该或更不应该至少与(((text)))(text)"的第一部分匹配.
Should not, or better, should match at least the first "(((text)))(text)" part.
实际上,我的正则表达式是:
Actually, my regexp is:
$regex = '/( ( (\() ([^[]*?) (?R)? (\)) ){0,}) /x';
但是它不能正常运行.如何解决?我哪里错了?谢谢!
But it does not work properly as I am expecting. How to fix that? Where am I wrong? Thanks!
推荐答案
当我找到此答案时,我无法弄清楚如何修改模式以使用我自己的分隔符,其中{
和}
.所以我的方法是使其更通用.
When I found this answer I wasn't able to figure out how to modify the pattern to work with my own delimiters which where {
and }
. So my approach was to make it more generic.
$delimiter_wrap = '~';
$delimiter_left = '{';/* put YOUR left delimiter here. */
$delimiter_right = '}';/* put YOUR right delimiter here. */
$delimiter_left = preg_quote( $delimiter_left, $delimiter_wrap );
$delimiter_right = preg_quote( $delimiter_right, $delimiter_wrap );
$pattern = $delimiter_wrap . $delimiter_left
. '((?:[^' . $delimiter_left . $delimiter_right . ']++|(?R))*)'
. $delimiter_right . $delimiter_wrap;
/* Now you can use the generated pattern. */
preg_match_all( $pattern, $subject, $matches );
这篇关于如何编写与嵌套括号匹配的递归正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!