Perl regular expression to match an IP address

Alternatively, you can use Data::Validate::IP, with the caveat that it won't recognize the port, so you'll have to split on :.

use strict;
use warnings;
use Data::Validate::IP;

my $ip_with_port="216.108.225.236:60099";
my $ip=(split /:/,$ip_with_port)[0];

my $validator=Data::Validate::IP->new;

if($validator->is_ipv4($ip))
{
  print "Yep, $ip is a valid IPv4 address.\n";
}
else
{
  print "Nope, $ip is not a valid IPv4 address.\n";
}

The output is:

Yep, 216.108.225.236 is a valid IPv4 address.

In the spirit of TIMTOWTDI here is another: the Regexp::Common::net portion of Regexp::Common may have regexen that you desire.


Change {1-3} to {1,3} same for {1-5} -> {1,5}

Tags:

Ip

Regex

Perl