0
$string  > show box detail
2 boxes:
1) Box ID: 1
       IP:                  127.0.0.1*
Interface:           1/1
 Priority:            31

如何从上面的字符串中提取 IP 并额外检查 * ?

4

4 回答 4

1

由于你只有一个看起来像 ip 的东西,你可以使用这个正则表达式:

(?:([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])

这就是它在Debuggex上的样子。

于 2013-03-28T18:09:42.393 回答
1

由于这看起来像一个文件,我的第一个假设是你想要一个单行:

perl -anlwe 'if ($F[0] eq "IP:") { print $F[1] }' input.txt 

否则,我建议使用软正则表达式,例如:

if ($foo =~ /IP:\s*(\S+)/) { 
    $ip = $1;
}
于 2013-03-28T18:13:10.483 回答
1

使用Regexp::Common

#!/usr/bin/env perl

use 5.012;
use strict;
use warnings;

use Regexp::Common qw( net );

while (my $line = <DATA>) {
    my @ips = ($line =~ /($RE{net}{IPv4})/g)
        or next;
    say @ips;
}

__DATA__
$string  > show box detail
2 boxes:
1) Box ID: 1
       IP:                  127.0.0.1*
Interface:           1/1
 Priority:            31
2) Box ID: 2
       IP:                  10.10.1.1
Interface:           1/1
 Priority:            31
于 2013-03-28T18:41:54.453 回答
0

您可以使用它来匹配(显示为可选 *)

((\d{1,3}\.){3}\d{1,3}\*?)
于 2013-03-28T18:10:42.453 回答