Regex 如何组合这些正则表达式?
四个完全相同的正则表达式。我用以下标量值替换字符串。这怎么能更有效率呢Regex 如何组合这些正则表达式?,regex,perl,Regex,Perl,四个完全相同的正则表达式。我用以下标量值替换字符串。这怎么能更有效率呢 $line =~ s/\[(receiver)\]/$receiver/g; $line =~ s/\[(place)\]/$place/g; $line =~ s/\[(position)\]/$position/g; $line =~ s/\[(company)\]/$company/g; 谢谢。考虑使用真正的模板系统。例如,这是非常容易的 撇开它不谈,你说你想让它更有效率。它目前的效率低下是一个问题吗?如果没有,就别
$line =~ s/\[(receiver)\]/$receiver/g;
$line =~ s/\[(place)\]/$place/g;
$line =~ s/\[(position)\]/$position/g;
$line =~ s/\[(company)\]/$company/g;
谢谢。考虑使用真正的模板系统。例如,这是非常容易的 撇开它不谈,你说你想让它更有效率。它目前的效率低下是一个问题吗?如果没有,就别管它 您可以一次完成所有操作:
my %subst = (
'receiver' => $receiver,
'place' => $place,
'position' => $position,
'company' => $company,
);
$line =~ s/\[(receiver|place|position|company)\]/$subst{$1}/g;
但是,如果,
$receiver
是“place”,那么这将起到不同的作用。对于组合正则表达式,您确实希望签出
更新:下面是一个更完整的示例:
my %subst = (
'receiver' => 'rcv',
'place' => 'plc',
'position' => 'pos',
'company' => 'cpy',
);
my $re = Regexp::Assemble->new->add(keys %subst);
my $str = "this is the receiver: [receiver] and this is the place: [place]";
$str =~ s/(?:\[($re)\])/$subst{$1}/g;
好的,让我看看,你想要什么: 如果要“计算”变量的值,即在字符串中找到的名称,则需要:
my $receiver = 'rcv';
my $place = 'plc';
my $position = 'pstn';
my $company = 'cmpn';
my $allVariableNames = join('|',qw(receiver place position company));
$line = '[receiver]';
$line =~ s/\[($allVariableNames)\]/'$'.$1/eg;
#$line =~ s/\[($allVariableNames)\]/eval('$'.$1)/eg; <- smarter and shorter variant
print $line,"\n"; #contain $receiver
print eval($line), "\n"; # evaluate ($receiver) => get rcv
my$receiver='rcv';
我的$place='plc';
我的$position='pstn';
我的$company='cmpn';
my$allVariableNames=加入(“|”,qw(接受者位置公司));
$line='[receiver]';
$line=~s/\[($allVariableNames)\]/'$。$1/eg;
#$line=~s/\[($allVariableNames)\]/eval(“$”.$1)/eg;获取rcv
这是完成此任务的另一种方法,请参见上面的回答,我通过以下几点了解到:
/\[(receiver|place|position|company)\]/${"$+"}/ge;
$receiver$place$position$company应该是全局变量(我们的)不幸的是,正则表达式没有那么聪明,因此,他们无法就每种情况下的适当替换做出决定。如果您使用Python的re库——我怀疑Perl也有类似的功能——您可以调用一个函数为每个匹配生成替换。+1用于显示组合表达式时语义的可能变化。一个是优点,新的语义可能是所需的语义。我将使用
map quotemeta,key%subst
add
接受正则表达式模式,而不是文本,但您的方法仅在键是文本时才有效。(实际上,在处理字符串而不是模式时,我会使用Regexp::List而不是Regexp::Assemble。)而不是s/\[($allVariableNames)\]/eval('$。$1)/eg
您可以使用s/\[($allVariableNames)\]/'$。$1/eeg代码>