Perl使用Regex搜索多个关键字

时间:2016-07-25 09:07:15

标签: perl hash key

我正在搜索文件中的关键字列表。我能够匹配整个关键字,但对于某些关键字,我需要匹配单词的第一部分。例如

/usr/local/cuda/include/host_config.h.

例如,使用上述关键字,我希望仅从以下输入中匹配DES AES https:// --- here it should match the word starting with https:// but my code considers the whole word and skips it. DESDES

https://

以下是我迄今为止所做的尝试:

DES some more words
DESTINY and more...
https://example.domain.com
http://anotherexample.domain.com # note that this line begins with http://, not https://

1 个答案:

答案 0 :(得分:0)

这是我认为你想要实现的目标的有效解决方案。如果没有,请告诉我:

use warnings;
use strict;
use feature qw/ say /;

my %keywords;

while(<DATA>){
    chomp;
    my ($key) = split;
    my $length = length($key);
    $keywords{$key} = $length;
}

open my $in, '<', 'in.txt' or die $!;


while(<$in>){
    chomp;
    my $firstword = (split)[0];

        for my $key (keys %keywords){
            if ($firstword =~ m/$key/){ 
                my $word = substr($firstword, 0, $keywords{$key});
                say $word;
            }
        }
}
__DATA__
Keywords:-
DES
AES 
https:// - here it should match the word starting with https:// but my code considers the whole word and skipping it.

对于包含以下内容的输入文件:

here are some words over multiple
lines
that may or
may not match your keywords:
DES DEA AES SSE
FOO https:
https://example.domain.com

这会产生输出:

 DES
 https://