0

I found online some regular expressions to match an IP address. I used the one that seemed the best and then changed it to match the network mask of that IP address. This is my code:

prefix = 'None'
while re.search(r'^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$', prefix) is None:
    prefix = raw_input('\n\n    Enter the prefix (destination IP) >  ')

mask = 'None'
while re.search(r'^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|0?)$', mask) is None:
    mask = raw_input('\n\n    Enter the network mask >  ')

I tested both regex's in www.regexr.com and both work fine, but when I run my script, the Python interpreter can't find a match in the mask variable, even when I insert a valid mask like 255.255.255.0. Because of this, it is always looping over the second question.

What is the problem here ? Should I not be using the "search" option ?

In summation: I need to verify a network mask provided by a user. It can be between 0.0.0.0 and 255.255.255.255 and it always has 4 elements separated by dots.

David
  • 271
  • 1
  • 15
  • https://docs.python.org/3/library/ipaddress.html – FHTMitchell May 18 '18 at 12:15
  • Those libraries are useful for validating an IP address, but I don't see how I could use them to validate Net Masks. Besides, I still don't understand why my code doesn't work if both regex's match – David May 18 '18 at 14:28

1 Answers1

0

Change your regex to this: r'^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$', prefix The problem is that in the original expression the \. is only part of one possible pattern in the OR operator.

And you could precompile it (with re.compile), as it's used multiple times.

  • My problem is not in the first loop it's in the second. There is some problem in the Second loop. I tested the regex in the [www.regexr.com](www.regexr.com) website and it worked, so it should work fine in the script. Can you test my code, please? – David May 18 '18 at 15:00
  • I tested it, for me it works fine. The first loop in its original form only works if the first three groups of the address are under 200. And in the second one, the final `|0?` means that the fourth group can be empty, I'm not sure that's what you wanted. Having a single 0 in any group is already covered by `[01]?[0-9][0-9]?` – Balázs Kovacsics May 18 '18 at 15:16
  • I applied the changes you suggested and it worked. I didn't even realize about that IP address limitation. The strangest part here is that the netmask loop started working again after a while, even before any change. Thank you for your help – David May 18 '18 at 15:45