问题描述
我一直在寻找一种方法来匹配正则表达式中的平衡括号,并在 Perl 中找到了一种使用递归正则表达式的方法:
I have been looking for a way to match balanced parenthesis in a regex and found a way in Perl, that uses a recursive regular expression:
my $re;
$re = qr{
(
(?:
(?> [^()]+ ) # Non-parens without backtracking
|
(??{ $re }) # Group with matching parens
)*
)
}x;
来自 perl 正则表达式网站.
有没有办法在 Ruby 或类似的语言中做到这一点?
Is there a way to do this in Ruby or a similar language?
更新:
对于那些感兴趣的人,这里有一些有趣的链接:
For those interested here are some interesting links:
Oniguruma 手册 - 来自 Sawa 的回答.
Oniguruma manual - from Sawa's answer.
推荐答案
是的.使用 oniguruma 正则表达式引擎,它内置于 Ruby 1.9 中,可安装在 Ruby 1.8 上,您可以做到这一点.您可以使用 (?...)
或 (?'name'...)
命名子正则表达式.然后在同一个正则表达式中使用 g
或 g'name'
调用子正则表达式.因此,您的正则表达式转换为 oniguruma 正则表达式将是:
Yes. With oniguruma regex engine, which is built in in Ruby 1.9, and is installable on Ruby 1.8, you can do that. You name a subregex with (?<name>...)
or (?'name'...)
. Then you call a subregex with g<name>
or g'name'
within the same regex. So your regex translated to oniguruma regex will be:
re = %r{
(?<re>
(
(?:
(?> [^()]+ )
|
g<re>
)*
)
)
}x
另请注意,PHP >=5 中的多字节字符串模块使用了 oniguruma 正则表达式引擎,因此您也可以这样做.
Also note that multi-byte string module in PHP >=5 uses oniguruma regex engine, so you will be able to do the same.
oniguruma 的手册在这里.
The manual for oniguruma is here.
这篇关于使用递归正则表达式(如 perl)匹配 Ruby 中的平衡括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!