http://www.perlmonks.org?node_id=396001


in reply to Regular Expression to Match IP Address

This should work for your needs:
my $range = qr/^ ( (?: # first 3 octets: (?: 2(?:5[0-5]|[0-4][0-9])\. ) # 200 - 255 | # or (?: 1[0-9][0-9]\. ) # 100 - 199 | # or (?: (?:[1-9][0-9]?|[0-9])\. ) # 0 - 99 ) {3} # above: three times (?: # 4th octet: (?: 2(?:5[0-5]|[0-4][0-9]) ) # 200 - 255 | # or (?: 1[0-9][0-9] ) # 100 - 199 | # or (?: [1-9][0-9]?|[0-9] ) # 0 - 99 ) $) /x; print "OK\n" if ($ip =~ /$range/);

Update:
Changed (?: [0-9][0-9]? ) to (?: [1-9][0-9]?|[0-9] ) so that it won't accidently match an octet with only 2 or more zeros or an octet with leading zero (i.e. 00.0.0.0 or 192.186.0.01)
Now this will only match addresses from 0.0.0.0 to 255.255.255.255 (assuming the address in $ip is already chomped)

Replies are listed 'Best First'.
Re^2: Regular Expression to Match IP Address
by codecookers (Initiate) on Mar 16, 2010 at 12:26 UTC
    if we want a simple version print"\n ip address " if ($s=~/((\d){1,3}\.){3}(\d){1,3}/) ;