0

I am attempting to create a regular expression check in python to validate an IPv4 address.

The rules for this address is that...

It must contain 4 numbers less or equal to 255, each of which are separated by a period.

For example...

243.2.176.12

or

1.1.1.1

I have created a regular expression to validate the format, i.e. the 3 digits between the periods. I am unsure of how to tackle the less than or equal to 255 limit.

My current code:

import re

MyRegex = "^\d{1,3}\\.\d{1,3}\\.\d{1,3}\\.\d{1,3}$"

while True:
  userip = input("Enter a string: ")

  if re.search(MyRegex,userip):
    print("Input accepted")
  else:
    print("Input Rejected")

Thanks in advance.

Link
  • 317
  • 1
  • 5
  • 17
  • `'\\.'.join(['('+'|'.join('%u' % x for x in range(1,256))+')']*4)` would work. The result can be reduced. – Dan D. Mar 23 '18 at 13:44
  • I'm not a big master of regex, i'd check that every element of the IP would be less or equal to 255: `foo = [x for x in ip.split('.') if int(x) <= 255]` and then just check the length of foo `len(foo)==4`. – 3nrique0 Mar 23 '18 at 13:56

0 Answers0