在perl中有没有办法忽略或省略正则表达式中哈希值的替换?

时间:2018-04-02 07:19:54

标签: regex perl

所以我在perl中有一个正则表达式,就像,

my $texttosub = "log10(blackcat)";
#the value of "blackcat" can be found in a hash called "%cats"
if ( $texttosub =~ s|([a-zA-Z][A-Za-z_0-9]+)|$cats{$1}|i ){          
  print ("\n", " The value of cat = ", eval ($texttosub) );
  ..do something..
}
sub log10{....}

我的问题是,我如何忽略" log10"并且只匹配" blackcat"替代?这样我就可以评估" $ texttosub"行和#34; blackcat"。

的log10值的行和打印

1 个答案:

答案 0 :(得分:2)

主要有两种方法:

  1. 匹配每个单词。如果它出现在哈希值中,则替换该值,否则不管它(即自己替换它):

    $texttosub =~ s{\b([a-zA-Z]\w*)\b}{ $cats{$1} // $1 }eg;
    
  2. 从您的哈希键构造一个正则表达式,只匹配这些词:

    use Data::Munge qw(list2re);
    my $regex = list2re keys %cats;
    $texttosub =~ s/\b($regex)\b/$cats{$1}/g;