2012-06-03 31 views
1

我想创建一个散列,其中的键是正则表达式,值是替换。我在MySQL数据库中完成了这个工作,创建了一个类似的结构,并使用了一个查询,比如“select * from $ 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/; 
} 
+1

[领带::哈希::正则表达式](http://p3rl.org/Tie::Hash::Regex), [Tie :: RegexpHash](http://p3rl.org/Tie::RegexpHash),[Tie :: REHash](http://p3rl.org/Tie::REHash) – daxim

+0

Tie :: Hash :: Regex是用于模糊匹配键,不使用正则表达式*作为键 – plusplus

回答

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'"