perl正则表达式提取ip从路由器show输出

时间:2011-04-04 15:11:14

标签: regex perl

我有路由器命令的输出:

Interface              IP-Address      OK? Method Status                Protocol
POS0/0/0               10.137.99.2    YES NVRAM  up                    up    

我想找一个正则表达式来识别IP地址:

我尝试过:

if ( $_ =~ m/(.*?)\s*?(.*?)\s*?(.*?)\s*?(.*)/i ){
    #print "$1->$2\n";
    $sources{$2}=$1;
}

然后使用$2作为ip。

然而,它不起作用;我哪里错了?

5 个答案:

答案 0 :(得分:6)

if ($_ =~ /\b(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\b/)
{
        print "IP: $1\n";
}

如果您只想获取第二列,那么可能应该使用split而不是正则表达式。获得字段#2:

@field = split(/ +/, $_);
print "$field[1]";

答案 1 :(得分:2)

PacoRG的答案很有效,但要解释你的错误:

请记住,* 可以匹配 no occurrence 。你告诉每个小组尽可能少地匹配,所以前3组没有捕获任何东西。此外,您希望尽可能多地抓取许多连续的空白字符,而不是少数。

保持RegEx与原版一样,您可以使用

m/(.+?)\s+(.+?)\s+(.+?)\s+(.+?)/i

答案 2 :(得分:2)

由于这是经常格式化的数据,您可能只需使用split:并按照以下方式获取:

#!/usr/bin/env perl
use Modern::Perl;


my $buff = "Interface              IP-Address      OK? Method Status                Protocol
POS0/0/0               10.137.99.2    YES NVRAM  up                    up  ";

for my $line (split /\n/,$buff)
{
  next if $line =~ /^Interface/;
  my ($interface, $ip) = (split /\s+/,$line)[0,1];
  say "IP $ip is on Interface $interface";
}

产生这个输出:

IP 10.137.99.2 is on Interface POS0/0/0

答案 3 :(得分:1)

错误就是那些最小的匹配。只需使用

($if, $ip) = split;
$sources{$ip} = $if;

答案 4 :(得分:0)

尝试:

m/.*?(\d+\.\d+\.\d+\.\d+).*/i