[英]Keep track of matches and check against condition
我有$entire_line
= "if varC > 0: varB = varC + 2"
我想我的正则表达式来查找以下内容: varC
, varB
, varB
在$entire_line
然后需要检查这些匹配项,以查看它们是否存在于HashMap
。 如果是这样,则应在匹配项后附加$
。
因此,输出应为:
"if $varC > 0: $varB = $varC + 2"
注意: 0
和2
不会出现在HashMap
。
目前,我有:
$entire_line =~ s/(\w+)/\$$1/g if (exists($variable_hash{$1}));
但是,这不能按预期方式工作,因为exists($variable_hash{$1})
的$1
exists($variable_hash{$1})
不引用以前的正则表达式: $entire_line =~ s/(\\w+)/\\$$1/g
有适当的方法来解决这个问题吗?
谢谢你的帮助。
使用/e
修饰符,并将代码放入替换部分:
$entire_line =~ s/(\w+)/exists $variable_hash{$1} ? $variable_hash{$1} : $1/ge;
如果我正确地回答了您的问题,并且您不需要执行变量值替换(如@choroba的回答),而只需将$
字符附加到已知变量中,并且如果%variables_hash
不太长,那么如何串联所有键的%variables_hash
带有|
字符以获得与所有已知变量匹配的正则表达式?
my %variable_hash = (
varA => 1,
# varB => 1, # commented out to check that it will not be replaced
varC => 1,
);
my $entire_line = "if varC > 0: varB = varC + 2;";
my $key_regex = join('|', map { quotemeta $_; } keys %variable_hash);
# $key_regex will contain "varA|varC"
$entire_line =~ s/\b($key_regex)\b/\$$1/g;
# prefix all matching substrings with $ character
print "$entire_line\n";
还要检查我对@choroba答案的评论。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.