我已使用http://www.regexe.com/來測試我創建的正則表達式,以從syslog
中提取日期和時間,它向我顯示正則表達式實際上是正確的,突出顯示日期和時間。然而,當我在Perl中嘗試這個時,我只返回了時間,而不是日期。正則表達式不完全匹配字符串
因此,例如從字符串Dec 9 12:45:36 osboxes NetworkManager[739]: <info> address 192.168.10.129
我將返回12:45:36
這裏是我的腳本:
use strict;
use warnings;
my $keywords = 'keywords.txt';
open(my $kw, '<:encoding(UTF-8)', $keywords)
or die "Could not open file '$keywords' $!"; # Open the file, throw an exception if the file cannot be opened.
chomp (my @keywordsarray = <$kw>); # Remove whitespace, and read it into an array
close($kw);# Close the file
my $syslog = 'syslog';
open(my $sl, '<:encoding(UTF-8)', $syslog)
or die "Could not open file '$keywords' $!"; # Open the file, throw an exception if the file cannot be opened.
chomp (my @syslogarray = <$sl>); # Remove whitespace, and read it into an array
close($sl);# Close the file
foreach my $line (@syslogarray)
{
foreach my $keyword (@keywordsarray)
{
if ($line =~ m/\Q$keyword\E/)
{
if ((my $date) = $line =~ m/[A-z]+\s{2}\d{1,}\s((\d{2}[:]){2}\d{2})/)
{
print "**". $keyword. "**". $date. "\n";
}
}
}
}
馬特,這不工作,或者我早些時候嘗試過。如果這有什麼不同,我使用Kali Linux。 – Simon
我剛剛在[IDEONE和您的正則表達式工作]上進行了測試(http://ideone.com/wduhGO)。 –
stribizhev我想要達到的是日期和時間,而不僅僅是日期。 – Simon