-5

I believe IP can only range from 0.0.0.0 to 255.255.255.255. I see lot's of complicated regex answers to match and validate IP addresses on stack overflow. Tell me what's wrong with mine.

ip = re.compile(r'[0-2]*[0-5]*[0-5]*\.[0-2]*[0-5]*[0-5]*\.[0-2]*[0-5]*[0-5]*\.[0-2]*[0-5]*[0-5]*\')

It works.

anika
  • 11

1 Answers1

1

I absolutely understand why you used [0-2]*[0-5]*[0-5]*, and I believe I made a similar mistake once. The problem here is that it can only match 000-055, 100-155, 200-255. The code you need should be something like this:

(?:(?:[01]*[0-9][0-9])|(?:2[0-4][0-9])|(?:25[0-5]))

For each three digit sequence.

In essence, you're telling the regex that the input should have either:

  • any number from 0 to 199, given by [01][0-9][0-9]
  • or any number from 200 to 249, given by 2[0-4][0-9]
  • or any number from 250 to 255, given by 25[0-5]
Robo Mop
  • 3,485
  • 1
  • 10
  • 23