Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 如何使用perl获取嵌套大括号内的值_Regex_Perl - Fatal编程技术网

Regex 如何使用perl获取嵌套大括号内的值

Regex 如何使用perl获取嵌套大括号内的值,regex,perl,Regex,Perl,我有一个字符串,在大括号中有表达式列表。我想通过将其拆分成一个数组来获取详细信息。 我试过这样做 #!/usr/bin/perl sub main() { my $string = <STDIN>; while ($string =~ /(\((?:(?1)|[^()]*+)++\))|[^()\s]++/g) { print "$&\n" } main(); InPut : (+ (+ 4 3) ( - 3 2) 5) Output should be : (+

我有一个字符串,在大括号中有表达式列表。我想通过将其拆分成一个数组来获取详细信息。 我试过这样做

#!/usr/bin/perl 
sub main() {
my $string = <STDIN>; 
while ($string =~ /(\((?:(?1)|[^()]*+)++\))|[^()\s]++/g) 
{
print "$&\n" 
}
main();

InPut : (+ (+ 4 3) ( - 3 2) 5)
Output should be : (+ (+ 3 4) ( - 2 3) 5)
(+ 3 4)
( - 2 3) 

有谁能帮我一下吗?

使用下面的表达式
/(?=(\(((?>[^()])+;(?1))*\)/g


查看此处的操作:

您无法同时获取所有嵌套级别的捕获,就像您无法使用类似
(++
(您只能获取最后一个字符)的内容获取多个捕获一样。您可以匹配最外层的括号并递归地继续匹配其内容。但我认为手动解析这样的东西更容易@m、 布特纳:没那么难,看看我下面的答案。如果OP看起来是无界嵌套,那就很难了。正则表达式没有进行无限嵌套的能力。只有解析器,即具有下推堆栈的有限状态自动化才能做到这一点。链接断开,请修复。Gad,我不敢相信有人愚蠢到在(ir)正则表达式中使用递归。这将使他们图灵完整。没有评论的地方。让我想起APL,一种只写的语言。@Lindrian the lookahead是个好主意+1.
4+3 =7 , 3-2 =1 , and then 7+1+5 = 13
Final output should be 13