Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

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
Node Status?
node history
Node Type: note [id://380565]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (5)
As of 2017-02-23 07:56 GMT
Find Nodes?
    Voting Booth?
    Before electricity was invented, what was the Electric Eel called?

    Results (340 votes). Check out past polls.