我正在學習Perl和試圖在書中練習。我也沒有很強的正則表達經驗。perl正則表達式量詞匹配使得意想不到的匹配
我試圖在文件中查找IP地址。我用一些IP地址編寫了一個隨機的log.txt文件,我還沒有完全試圖驗證,但我試圖匹配四個1到3位數字,用'。'隔開。
我的代碼需要一個文件名並在該文件中逐行運行,併爲IP地址提取匹配。
這裏是我的代碼:
#!/usr/bin/perl
print "poop\n";
foreach my $arg(@ARGV) {
print "$arg\n";
}
print "The file name is: $ARGV[0]\n";
$file = $ARGV[0];
open my $info, $file or die "Could not open $file: $!";
while ($line = <$info>) {
print $line;
if($line =~ /(\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3})/){
my $digit = $1;
print "A match is: $digit \n";
}
}
close $info;
這裏是我的日誌文件:
a b c d e f g h i j k l m n o p q r s t u v w x y z
1 2 3 4 5 6 7 8 9 0
apple
cat
banana
chariot
zebra
yellow
123.543.98.32
2.2.3.4
1.3.4.55
1.2.3.454
1.1.1.1
22.22.22.22
333.333.333.333
012.345.678.910
012.345.678.91
012.345.678.9
this shouldn't work!!::::
1234.41.123.0
這裏是我的運行結果:
$ perl stringsTest.pl ./log.txt
poop
./log.txt
The file name is: ./log.txt
a b c d e f g h i j k l m n o p q r s t u v w x y z
1 2 3 4 5 6 7 8 9 0
A match is: 1 2 3 4
apple
cat
banana
chariot
zebra
yellow
123.543.98.32
A match is: 123.543.98.32
2.2.3.4
A match is: 2.2.3.4
1.3.4.55
A match is: 1.3.4.55
1.2.3.454
A match is: 1.2.3.454
1.1.1.1
A match is: 1.1.1.1
22.22.22.22
A match is: 22.22.22.22
333.333.333.333
A match is: 333.333.333.333
012.345.678.910
A match is: 012.345.678.910
012.345.678.91
A match is: 012.345.678.91
012.345.678.9
A match is: 012.345.678.9
this shouldn't work!!::::
1234.41.123.0
A match is: 1234.41.123
這最後一場比賽是一個我被困惑了。
我認爲我使用的量詞應該將匹配限制爲1到3位數。我懷疑貪婪是一個嫌疑犯。有人可以向我解釋爲什麼這個匹配,而忽略了「.0」?
1234.41.123.0
A match is: 1234.41.123