在键中使用特殊字符进行Perl哈希替换 [英] Perl hash substitution with special characters in keys
问题描述
我当前的脚本将带有一个表达式,例如:
My current script will take an expression, ex:
my $expression = '( a || b || c )';
并使用sub/replace遍历每个布尔输入组合,如下所示:
and go through each boolean combination of inputs using sub/replace, like so:
my $keys = join '|', keys %stimhash;
$expression =~ s/($keys)\b/$stimhash{$1}/g;
例如,表达式可以保存,
So for example expression may hold,
( 0 || 1 || 0 )
这很好.
但是,我想允许变量(也在%stimhash中)包含标记*.
However, I would like to allow the variables (also in %stimhash) to contain a tag, *.
my $expression = '( a* || b* || c* )';
此外,打印stimhash的键将返回:
Also, printing the keys of the stimhash returns:
a*|b*|c*
不能正确地用/替换特殊字符*.
它给出以下警告:
It is not properly substituting/replacing with the extra special character, *.
It gives this warning:
%stimhash中未初始化的值在替换迭代器中的使用
Use of uninitialized value within %stimhash in substitution iterator
我尝试使用quotemeta(),但到目前为止效果不佳.
它将删除这些值.替换后的示例如下:
I tried using quotemeta() but did not have good results so far.
It will drop the values. An example after the substitution looks like:
( * || * || * )
任何建议都值得赞赏,
约翰
推荐答案
问题1
您使用模式a*
认为它仅与a*
相匹配,但是a*
表示"0或更多a
".您可以使用quotemeta
将文本转换为与该文本匹配的正则表达式模式.
Problem 1
You use the pattern a*
thinking it will match only a*
, but a*
means "0 or more a
". You can use quotemeta
to convert text into a regex pattern that matches that text.
替换
my $keys = join '|', keys %stimhash;
使用
my $keys = join '|', map quotemeta, keys %stimhash;
问题2
\b
基本上是
(?<!\w)(?=\w)|(?<=\w)(?!\w)
但是*
(如空格)不是文字字符.解决方法可能是替换
But *
(like the space) isn't a word character. The solution might be to replace
s/($keys)\b/$stimhash{$1}/g
使用
s/($keys)(?![\w*])/$stimhash{$1}/g
尽管以下内容对我来说更有意义
though the following make more sense to me
s/(?<![\w*])($keys)(?![\w*])/$stimhash{$1}/g
我个人会用
s{([\w*]+)}{ $stimhash{$1} // $1 }eg
这篇关于在键中使用特殊字符进行Perl哈希替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!