+ 2
Regular expression 4 matching IP adresses
Hey, guys, have a little question. How to correctly match an ip address with regular expression? I have tried by myself, but something went wrong. Here's my code: import re ipfilter = r"^(([01])?([0-9])?[0-9]|2[0-4][0-9]|25[0-5]\.){3}(([01])?([1-9])?[0-9]|2[0-4][0-9]|25[0-5])
quot; target = input('Enter IP here: ') if re.match(ipfilter, target): print('correct address') else: print('wrong address') Unfortunately, this RE matches only last part of my RE (25[0-5]). So, where is my mistake?5 Answers
+ 3
You could shortened your regular expression as this:
ipfilter = r"^((25[0-5]|2[0-4]\d|[01]?\d\d?)(\.(?!$)|$)){4}quot;
+ 2
Hi, in the first part of regex you should separate the number match from dot match otherwise the rule can't matching the number/dot repetition
Fix the regex simply by adding a parenthesis before \.
^((([01])?([0-9])?[0-9]|2[0-4][0-9]|25[0-5])\.){3}(([01])?([1-9])?[0-9]|2[0-4][0-9]|25[0-5])$
the IP with 255 was captured by the second part of your regex.
+ 1
Not sure: I recently discover it in a code... I can only suppose that (\.(?!$)|$) should be interpreted as 'dot authorized if not last char' ('dot if not last char or nothing')
0
Thank you for a great answer, that really helps!
0
visph, can you explain (?!$) group?