Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: Regexp to match IP address

by dsb (Chaplain)
on Aug 06, 2004 at 14:31 UTC ( #380565=note: print w/ replies, xml ) Need Help??


in reply to Regexp to match IP address

Where's japhy when you need 'em. :)

I guess it kind of depends on how concerned you are with the validity of your data. Testing for 4 1-3 digit numbers seperated by dots is easy:

m/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\$/;
If you are interested making sure IP's are valid, you could do a couple of things.

One, using the above regex, you could grab the digits and test them individually.

use strict; my @nums; my $IP = "127.0.0.1" (@nums) = $IP =~ m/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/; # test each for <= 255 here. # also make sure its not 0.0.0.0
Or you could use a more complicated regex to test for validity during the pattern matching. From O'Reilly's Mastering Regular Expressions:
m/^([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\. ([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])$/;
UPDATE: I just realized this was my 150th post. Yay for me. :)


dsb
This @ISA my cool %SIG


Comment on Re: Regexp to match IP address
Select or Download Code
Re^2: Regexp to match IP address
by kamleein (Initiate) on Mar 26, 2014 at 15:12 UTC
    Hi below code validates the IP adress. Please do let me know how this can be enhanced so that it is more readable. The validations considered are listed below. 1) If the length of any part of the IP adress seperated by the decimal is more than one digit, then it should not start with zero. 2) The first part of the IP adress seperated by the decimal cannot be zero. 3) Any part of the IP adress seperated by the decimal cannot be more than 255. 4) IP address should contain only 3 decimals. 5) The numbers cannot be negative. print "Enter the IP address : "; $ip = <stdin>; if($ip =~ /^(3-9\d?|1\d?\d?|2(0-5?0-5?|6-9?))\.(0|3-9\d?|(1\d?\d?|2(0-5?0-5?|6-9?)))\.(0|3-9\d?|(1\d?\d?|2(0-5?0-5?|6-9?)))\.(0|3-9\d?|(1\d?\d?|2(0-5?0-5?|6-9?)))$/) { print "Correct\n"; } else { print "Wrong\n"; }

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://380565]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (11)
As of 2014-09-22 12:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (191 votes), past polls