删除parens中的文本,但不删除Perl中的parens

Jam*_*mes 6 string perl

好吧,我得到了一个奇怪的,我已经干了一段时间(下午脑子里不起作用我猜).

有没有人知道要解析一个字符串并删除parens中的所有文本而不删除parens本身...但删除内部发现的parens.

即.

myString = "this is my string (though (I) need (help) fixing it)"
Run Code Online (Sandbox Code Playgroud)

通过我想要的运行它看起来像:

myString = "this is my string ()"
Run Code Online (Sandbox Code Playgroud)

保持那两个parens非常重要.

Chr*_*ley 10

模块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;
Run Code Online (Sandbox Code Playgroud)

输出:

111()55
a()g()()
this is my string ()

  • 哇哦,酷!Regexp::Common 的冗长的正则表达式经常让我感到惊讶...... (2认同)

Sin*_*nür 6

您需要转义括号以防止它们启动捕获组.该模式\(.+\)匹配以a开头并以a (结尾的最长子字符串).这会吞噬到最后一切,)包括任何干预括号.最后,我们用一个只包含的字符串替换该字符串():

#!/usr/bin/perl

use strict; use warnings;

my $s = "this is my string (though (I) need (help) fixing it)";

$s =~ s{\(.+\)}{()};

print "$s\n";
Run Code Online (Sandbox Code Playgroud)


J.J*_*.J. 2

如果您想使用正则表达式而不使用 Regexp::Common。查看“环顾四周”功能。它是随 Perl 5 引入的。您可以在regular-expressions.info阅读有关“Look Ahead”和“Look Behind”的更多信息。《掌握正则表达式》一书中还有一个关于“Look around”的章节。请参阅第 59 页。

#!/usr/bin/env perl

use Modern::Perl;

my $string = 'this is my (string (that)) I (need help fixing)';

$string =~ s/(?<=\()[^)]+[^(]+(?=\))//g;

say $string;
Run Code Online (Sandbox Code Playgroud)