0

I am trying to validate an IP address. Following is the code. Can anyone please tell me what is wrong in the code?

import re

ip = '355.4'

m = re.match('^((?:1?\d{0,2}|2[0-4]\d{1}|25[0-5]).){3}(?:1?\d{0,2}|2[0-4]\d{1}|25[0-5])$', ip)
if m:
    print "correct"
    print m.groups()
else:
    print "wrong"

According to the IP given, it should print wrong as output but it prints correct ('4',) as the output.

1
  • 1
    Possibly interesting: if you want help debugging the regex, I've thrown it into a visualizer. It may be of help now, or in the future! Commented Mar 11, 2015 at 11:42

4 Answers 4

2

If you are allowed to not to use regex, you can use python's socket package . inet_aton("string") converts the string to ip address,if this is not valid ip then it will throw exception.

Simple example I have tried:

    import socket

    def check_valid(address):
        try:
            socket.inet_aton(address)
            return address.count('.') == 3
        except socket.error:
            return False

    if __name__ == "__main__":
        print check_valid("192.168.1.255")

It will check all valid ip address like 192.168.1.257 is invalid while 192.168.1.255 is valid.

Sign up to request clarification or add additional context in comments.

Comments

0

I was making a mistake by not giving \ before . which was resulting in it matching any character.

import re

ip = '255.25.2.256'

m = re.match('^((?:1?\d{0,2}|2[0-4]\d{1}|25[0-5])\.){3}(?:1?\d{0,2}|2[0-4]\d{1}|25[0-5])$', ip)
if m:
    print "correct"
    print m.groups()
else:
    print "wrong"

Comments

0
len(ip.split(".")) == 4 and all(map(lambda o: o.isdigit() and int(o) <= 255, ip.split(".")))

Never ever use regexps in code. Please.

13 Comments

I wouldn't say "never", but certainly not for a problem such as this. +1
Why shouldn't I use regex?
because they are unreadable. it's write-only stuff. it's ok to use them in editor or in shell - for 1-time use (which I'm doing dozens times per day e.g.), but not in code.
You should also not repeat yourself, you are splitting twice just to put it all into one line.
@iced, the is the point, not everything can or should be a single line of code. Also regex has it's uses in code so saying to never use it is simply wrong
|
0

You should remove the optionnal quantifier ? in :1?. Otherwise .... is a valid ip address.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.