regex - perl 获取嵌套函数和参数(text::balanced 或普通 perl)

标签 regex perl perl-module

我有一个包含以下内容的文本文件,我想使用 perl 提取数组或其他数据结构中的嵌套函数(包括 rootfunc)。

输入文件内容:

rootfunc aaa with string1 {
    blah blah
    subfunc bbb (different parameters) {
        blah blah
    }
    subfunc others_in_aaa (different parameters) {
        blah blah
    }
}

rootfunc ccc with string2 {
    blah blah
    if (blah) {
        blah blah
    } else {
        blah blah
    }
    subfunc others_in_ccc (different parameters) {
        blah blah
    }
}

rootfunc others with stringothers {
    blah blah
    subfunc others_in_others (different parameters) {
        blah blah
    }
}

我想提取所有的 rootfunc 和 subfunc,输出如下:

预期输出文件(不,if/else 也被删除):

rootfunc aaa with string1 {
    subfunc bbb (different parameters) {
    }
    subfunc others_in_aaa (different parameters) {
    }
}

rootfunc ccc with string2 {
    subfunc others_in_ccc (different parameters) {
    }
}

rootfunc others with stringothers {
    subfunc others_in_others (different parameters) {
    }
}

使用下面的 perl 脚本,我只能提取 rootfunc 括号中的内容,然后获取 subfunc 中的内容,但是 rootfunc 名称/参数和 subfunc 名称/参数丢失了:

PERL 脚本:

use Text::Balanced qw(extract_multiple extract_bracketed);

open(FILE, "/tmp/a") || die "Unable to open /tmp/a: $!\n";
{
    local $/=undef;
    my $file = <FILE>;
}
close(FILE);
my @array = extract_multiple($file, [sub{extract_bracketed($_[0], '{}')},], undef, 1);

有什么方法可以得到想要的输出吗?谢谢,

最佳答案

假设subfunc是关键字,可以使用正则表达式。我把它分成两个///,但它可以合并。

sub squeeze {
    my( $s ) = @_;
    $s =~ s/(?<=\{\n)[^(){}]*?(?= *subfunc)//sg;
    $s =~ s/(?<=\{)[^(){}]*?(?=\})//sg;
    return $s;
}

如果有嵌套的大括号,那么 Text::Balanced 可以与正则表达式结合使用:

sub squeeze {
    my( $s ) = @_;
    my $out = '';
    while( $s =~ s/^(\s*rootfunc[^{]*\{).*?(?=\s*subfunc)//s ){
        $out .= $1 ;
        while( $s =~ s/^(\s*subfunc[^)]+\)\s*).*?(?=\{)//s ){
            $out .= $1;
            my( $ext, $rem ) = extract_bracketed( $s, '{' );
            $out .= "{}";
            $s = $rem;
        }
        $out .= "}";
        if( $s =~ s/^(\s+\})//s ){
            $s .= $1;
        }
    } 
    return $out;
}

关于regex - perl 获取嵌套函数和参数(text::balanced 或普通 perl),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36224020/

相关文章:

multithreading - 如何在 Perl 中处理任何事件、RabbitMQ(心跳)和长时间运行的作业?

perlre 长度限制

Java IO 模式识别

用其他东西替换字符串中第 N 次出现的字符

android - 如何使用 perl 存储和显示 ISO-8859-1 和 UTF8 字符

perl - "Devel::Cover: Can' t 打开 test.pl 用于 MD5 摘要 : No such file or directory"after switching user

linux - 无法在@INC 中找到 Cairo.pm

Perl 安装 PAR :Packer Problems

javascript - 用于查找字符串中等距字符的 RegExp 代码

perl - 安装 perl 模块和复制整个文件夹有什么区别?