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

How to extract IP from above string withc additional check for * ?

Dcoder
  • 379
  • 2
  • 7
  • 13

4 Answers4

1

Since you only have one thing that looks like an ip, you can just use this regex:

(?:([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])

This is what it looks like on Debuggex.

Sergiu Toarca
  • 2,697
  • 20
  • 24
  • +1 This is actually more specific than the regex I posted (which only looked for digits not specific 0-255 values). I was going for quick and dirty :) – Mike Brant Mar 28 '13 at 18:12
1

Since that looks like a file, my first assumption is that you want a one-liner:

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

Otherwise, I would suggest a soft regex such as:

if ($foo =~ /IP:\s*(\S+)/) { 
    $ip = $1;
}
TLP
  • 66,756
  • 10
  • 92
  • 149
1

Use 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
Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339
0

You can use this to match (shown with optional *)

((\d{1,3}\.){3}\d{1,3}\*?)
Mike Brant
  • 70,514
  • 10
  • 99
  • 103
  • This is incorrect. It will match, say, `602.0.3.5`, which is not a valid ipv4 address. However, I imagine for the OP's use, it's good enough. – Sergiu Toarca Mar 28 '13 at 18:13
  • @SergiuToarca Yes I understand that, but since this string is likely to only be populated with valid IP addresses, I presented this as a quick and dirty solution. It seems the interest was more in extraction of the value that is was in validation of the value. – Mike Brant Mar 28 '13 at 18:15
  • You are right @MikeBrant :) I am looking on extraction part only – Dcoder Mar 28 '13 at 18:49