【发布时间】:2015-10-19 16:54:50
【问题描述】:
我正在努力学习 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
【问题讨论】: