Skip to content Skip to sidebar Skip to footer

Finding Valid Ip Addresses With Regex

I have the following string: text = '10.0.0.1.1 but 127.0.0.256 1.1.1.1' and I want to return the valid IP addresses, so it should only return 1.1.1.1 here since 256 is higher tha

Solution 1:

Here is a python regex that does a pretty good job of fetching valid IPv4 IP addresses from a string:

import re
reValidIPv4 = re.compile(r"""
    # Match a valid IPv4 in the wild.
    (?:                                         # Group two start-of-IP assertions.
      ^                                         # Either the start of a line,
    | (?<=\s)                                   # or preceeded by whitespace.
    )                                           # Group two start-of-IP assertions.
    (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)    # First number in range 0-255 
    (?:                                         # Exactly 3 additional numbers.
      \.                                        # Numbers separated by dot.
      (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)  # Number in range 0-255 .
    ){3}                                        # Exactly 3 additional numbers.
    (?=$|\s)                                    # End IP on whitespace or EOL.
    """, re.VERBOSE | re.MULTILINE)

text = "10.0.0.1.1 but 127.0.0.256 1.1.1.1"
l = reValidIPv4.findall(text)
print(l)

Post a Comment for "Finding Valid Ip Addresses With Regex"