-2

I'm making a code to retrieve IP adresses in a text file, but i have an issue with the regex part:

import re

print re.search(r"[0-255].[0-255].[0-255].[0-255]","5.39.0.0")

this returns None but it should return <_sre.SRE_Match object at 0x0000000001D7C510> (because "5.39.0.0" matches with the expression). If I replace 39 with 0 it works.

jonrsharpe
  • 107,083
  • 22
  • 201
  • 376

2 Answers2

1

Your regular expression wont wort for many reasons (see the comments).

The dots indicate that any character can be used you want \.

Try this regular expression:

(?:(?:[01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])

As a reference check this site, there are similar examples: Regular Experession Examples

P.S.: There are several testing sites on the web for regular expressions, you should use them, for example: Regex101

Edit: The conditional options in the last group must be inverted, if not the match of 2** will get with the two first characters throught first condition, ex: 255.255.255.250 will be matched as 255.255.255.25 (the last digit is lost). Also using non capturing groups in regular expressions is recomended in cases where individual groups (used for alternatives or counting) have no meaning or are not needed.

jrodriguez
  • 63
  • 1
  • 5
Roman
  • 2,822
  • 4
  • 41
  • 88
0

Ok, i forgot some important stuffs, here is the solution:

[0-9]{1,3}[.][0-9]{1,3}[.][0-9]{1,3}[.][0-9]{1,3}