2012-06-03 56 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'"