Search code examples
pythonregexip-addressnetmask

Python Regex search for Network Mask


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.


Solution

  • 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.