所以我在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值的行和打印答案 0 :(得分:2)
主要有两种方法:
匹配每个单词。如果它出现在哈希值中,则替换该值,否则不管它(即自己替换它):
$texttosub =~ s{\b([a-zA-Z]\w*)\b}{ $cats{$1} // $1 }eg;
从您的哈希键构造一个正则表达式,只匹配这些词:
use Data::Munge qw(list2re);
my $regex = list2re keys %cats;
$texttosub =~ s/\b($regex)\b/$cats{$1}/g;