我在搜索一個文件中的關鍵字列表。我可以匹配整個關鍵字,但對於某些關鍵字,我需要匹配單詞的第一部分。例Perl使用正則表達式搜索多個關鍵字
DES
AES
https:// --- here it should match the word starting with https:// but my code considers the whole word and skips it.
例如使用上述關鍵字,我會想匹配DES
,DES
和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://
這是我到目前爲止已經試過:
use warnings;
use strict;
open STDOUT, '>>', "my_stdout_file.txt";
#die qq[Usage: perl $0 <keyword-file> <search-file> <file-name>\n] unless @ARGV == 3;
my $filename = $ARGV[2];
chomp ($filename);
open my $fh, q[<], shift or die $!; --- This file handle Opening all the 3 arguments. I need to Open only 2.
my %keyword = map { chomp; $_ => 1 } <$fh>;
print "$fh\n";
while (<>) {
chomp;
my @words = split;
for (my $i = 0; $i <= $#words; $i++) {
if ($keyword{^$words[ $i ] }) {
print "Keyword Found for file:$filename\n";
printf qq[$filename Line: %4d\tWord position: %4d\tKeyword: %s\n],
$., $i, $words[ $i ];
}
}
}
close ($fh);
程序如何知道你是否希望有一個完整的詞匹配或只是部分匹配? – Borodin