我正在尝试创建一个哈希,其中键是正则表达式,值是替换。我在一个MySQL数据库中创建了一个类似的结构,并使用查询,如“select * from table where $ lookup RLIKE`key`”,它工作正常。我想在perl脚本中尝试相同的操作,看看我是否可以让它更有效地运行。我意识到我可以将它作为一个循环并检查每个键但不要;这就是为什么我构建了正则表达式字符串。我无法弄清楚的唯一部分是如何让perl给我回复匹配的正则表达式(更改)的部分...
%s = (
'^mynumbers-(\d+)$' => 'thenumber-$1' ,
'^myletters-([a-zA-Z])$' => 'theletter-$1'
);
#build a string of the hash keys into a regex
while (keys %s) {
$regex_string.="($_)|";
}
#this is the input that will be looked up
$lookup = 'mynumbers-123';
if ($lookup=~/$regex_string/) {
print "found->$lookup in the regex\n";
$matched_regex = $i_dont_know;
### How do I know which subgroup it matched???
### I need to know so I can do this
$lookup=~s/\Q$i_dont_know\E/\Q$s{$matched_regex}\E/;
}
答案 0 :(得分:3)
正如daxim指出的那样,有几种CPAN模块可以满足您的需求。 Tie::RegexpHash
就是其中之一:
<强>概要强>
use Tie::RegexpHash; my %hash; tie %hash, 'Tie::RegexpHash'; $hash{ qr/^5(\s+|-)?gal(\.|lons?)?/i } = '5-GAL'; $hash{'5 gal'}; # returns "5-GAL" $hash{'5GAL'}; # returns "5-GAL" $hash{'5 gallon'}; # also returns "5-GAL" my $rehash = Tie::RegexpHash->new(); $rehash->add( qr/\d+(\.\d+)?/, "contains a number" ); $rehash->add( qr/s$/, "ends with an \`s\'" ); $rehash->match( "foo 123" ); # returns "contains a number" $rehash->match( "examples" ); # returns "ends with an `s'"