Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

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:

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 = "" (@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
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. :)

This @ISA my cool %SIG

Replies are listed 'Best First'.
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?

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

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (2)
As of 2021-12-05 13:20 GMT
Find Nodes?
    Voting Booth?
    R or B?

    Results (31 votes). Check out past polls.