无与伦比(在正则表达式中

时间:2014-09-25 05:03:55

标签: regex perl

我收到错误:

Unmatched ( in regex; marked by <-- HERE in m/( <-- HERE

我的代码如下:

if ($entire_line =~ /(\()[^\+\-\*\/]*(\))/){
    $entire_line =~ s/$1//;
    $entire_line =~ s/$2//;
}

$entire_line可能看起来像这样:

print ( factor0 ) * (factor1) * factor2, " a b c d"

我尝试删除(),如果它们不包含数字运算符+ - / *

结果:print factor0 * factor1 * factor2, " a b c d"

感谢您的帮助。

3 个答案:

答案 0 :(得分:0)

你几乎就在那里,只需抓住内部部分并用匹配的字符替换匹配的字符。

正则表达式:

(\()([^\+\-\*\/]*)(\))

替换字符串:

$2

DEMO

use strict;
use warnings;

while(my $line = <DATA>) {
    $line =~ s/(\()([^\+\-\*\/]*)(\))/$2/g;
    print $line;;
}

__DATA__
print ( factor0 ) * (factor1) * factor2, (factor1*factor2) " a b c d"

<强>输出:

print  factor0  * factor1 * factor2, (factor1*factor2) " a b c d"

答案 1 :(得分:0)

如果您只想删除paranthesis,如果输入文件中存在整行,请尝试以下代码:( Perl one liner:substitution)

<强> INPUTFILE:

print ( factor0 ) * (factor1) * factor2, " a b c d" (factor0 + factor1 - factor2)

代码:( Perl One班轮)

perl -lne "if($_ =~ s/(\()([^\+\-\*\/]*)(\))/$2/isg) { print $_;} else { print $_;}" Inputfile 

<强>输出:

print  factor0  * factor1 * factor2, " a b c d" (factor0 + factor1 - factor2)

答案 2 :(得分:0)

您的目标可能被误导,因为您可能不会考虑边缘情况。

但是,我建议使用(?PARNO)处理平衡括号。

以下尝试剥离不包含puntuation的平衡括号。

use strict;
use warnings;
use autodie;

while (<DATA>) {
    simplify_parens($_);
    print;
}

sub simplify_parens {
    s{ \( ( (?: [^()]+ | \( (?1) \) )* ) \) }{
        simplify_parens( my $str = $1 );
        $str =~ m{[*/+-]} ? "($str)" : $str;
    }exg for @_;
}
__DATA__
print ( factor0 ) * (factor1) * factor2, " a b c d"
print ( factor0 ) * (((factor1))) * factor2, " a b c d"

输出:

print  factor0  * factor1 * factor2, " a b c d"
print  factor0  * factor1 * factor2, " a b c d"

嗯,这比建议的其他解决方案更好。

但是,如果数据包含(((factor1 + factor3)))这样的表达式怎么办?不应该剥离外部的两组括号,只保留最后一个内部括号吗?

要实现这种功能,请执行以下操作:

use strict;
use warnings;
use autodie;

while (<DATA>) {
    simplify_parens($_);
    print;
}

sub simplify_parens {
    my $clean = 1;
    for (@_) {
        my @tokens = split m{ \( ( (?: [^()]+ | \( (?1) \) )* ) \) }x;
        for my $i ( 0 .. $#tokens ) {
            if ( $i % 2 ) {
                $tokens[$i] = "($tokens[$i])" if !simplify_parens( $tokens[$i] );
            } else {
                $clean &&= $tokens[$i] !~ m{[*/+-]};
            }
        }
        $_ = join '', @tokens;
    }
    return $clean;
}

__DATA__
print ( factor0 ) * (factor1) * factor2, " a b c d"
print ( factor0 ) * (((factor1))) * factor2, " a b c d"
print ( factor0 ) * (((factor1 + factor3))) * factor2, " a b c d"

输出:

print  factor0  * factor1 * factor2, " a b c d"
print  factor0  * factor1 * factor2, " a b c d"
print  factor0  * (factor1 + factor3) * factor2, " a b c d"

这样做效果更好。然而,我想要传达的主要教训是,这可能是一个比它最初出现的更大,更复杂的任务。