Regular expression 4 matching IP adresses | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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?

10th Jan 2018, 5:59 AM
Павел Лукашик
Павел Лукашик - avatar
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;
10th Jan 2018, 6:38 AM
visph
visph - avatar
+ 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.
9th Jan 2018, 10:58 PM
AtoMX
AtoMX - avatar
+ 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')
10th Jan 2018, 7:17 AM
visph
visph - avatar
0
Thank you for a great answer, that really helps!
10th Jan 2018, 6:22 AM
Павел Лукашик
Павел Лукашик - avatar
0
visph, can you explain (?!$) group?
10th Jan 2018, 7:10 AM
Павел Лукашик
Павел Лукашик - avatar