【问题标题】:Removing text inside parens, but not the parens in Perl删除括号内的文本,但不删除 Perl 中的括号
【发布时间】:2010-02-12 22:57:03
【问题描述】:

好的,我有一个奇怪的东西,我已经玩了一段时间了(我猜周五下午的头脑不灵了)。

有谁知道解析字符串并删除括号内的所有文本而不删除括号本身...但删除内部发现的括号。

即。

myString = "this is my string (though (I) need (help) fixing it)"

在运行完我想要的样子后:

myString = "this is my string ()"

将这两个括号保留在那里非常重要。

【问题讨论】:

    标签: perl string


    【解决方案1】:

    Regexp::Common 模块处理超过 1 个顶级括号。

    use strict;
    use warnings;
    use Regexp::Common qw/balanced/;
    
    my @strings = (
        '111(22(33)44)55',
        'a(b(c(d)(e))f)g(h)((i)j)',
        'this is my string (though (I) need (help) fixing it)',
    );
    
    s/$RE{balanced}{-parens=>'()'}/()/g for @strings;
    
    print "$_\n" for @strings;
    

    输出:

    111()55 a()g()() 这是我的字符串 ()

    【讨论】:

    • 哇,酷! Regexp::Common 经常以其冗长的正则表达式集让我感到惊讶...
    • 我并不惊讶它可以在一行 Perl 中完成,但我很惊讶它是可读的!
    【解决方案2】:

    您需要转义括号以防止它们启动捕获组。模式\(.+\) 匹配以( 开头并以) 结尾的最长子字符串。这将吞噬所有内容,直到最后一个),包括任何插入的括号。最后,我们将该字符串替换为仅包含 () 的字符串:

    #!/usr/bin/perl
    
    use strict; use warnings;
    
    my $s = "this is my string (though (I) need (help) fixing it)";
    
    $s =~ s{\(.+\)}{()};
    
    print "$s\n";
    

    【讨论】:

    • 只要只有一组顶级括号,它就可以工作。否则,像“this is my (string (that)) I (need help fix)”这样的字符串会变成“this is my ()”而不是“this is my () I ()”
    【解决方案3】:

    如果您想使用正则表达式而不使用 Regexp::Common。查看“环顾四周”功能。它是在 Perl 5 中引入的。 您可以在regular-expressions.info 阅读有关“向前看”和“向后看”的更多信息。 《精通正则表达式》一书中也有关于“环顾四周”的部分。请看第 59 页。

    #!/usr/bin/env perl
    
    use Modern::Perl;
    
    my $string = 'this is my (string (that)) I (need help fixing)';
    
    $string =~ s/(?<=\()[^)]+[^(]+(?=\))//g;
    
    say $string;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-17
      • 2021-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-20
      • 1970-01-01
      • 2020-08-18
      相关资源
      最近更新 更多