Check If a String Matches an Ip Address Pattern in Python

check if a string matches an IP address pattern in python?

update: The original answer bellow is good for 2011, but since 2012, one is likely better using Python's ipaddress stdlib module - besides checking IP validity for IPv4 and IPv6, it can do a lot of other things as well.</update>

It looks like you are trying to validate IP addresses. A regular expression is probably not the best tool for this.

If you want to accept all valid IP addresses (including some addresses that you probably didn't even know were valid) then you can use IPy (Source):

from IPy import IP
IP('127.0.0.1')

If the IP address is invalid it will throw an exception.

Or you could use socket (Source):

import socket
try:
socket.inet_aton(addr)
# legal
except socket.error:
# Not legal

If you really want to only match IPv4 with 4 decimal parts then you can split on dot and test that each part is an integer between 0 and 255.

def validate_ip(s):
a = s.split('.')
if len(a) != 4:
return False
for x in a:
if not x.isdigit():
return False
i = int(x)
if i < 0 or i > 255:
return False
return True

Note that your regular expression doesn't do this extra check. It would accept 999.999.999.999 as a valid address.

ip address validation in python using regex

Use anchors instead:

aa=re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$",ip)

These make sure that the start and end of the string are matched at the start and end of the regex. (well, technically, you don't need the starting ^ anchor because it's implicit in the .match() method).

Then, check if the regex did in fact match before trying to access its results:

if aa:
ip = aa.group()

Of course, this is not a good approach for validating IP addresses (check out gnibbler's answer for a proper method). However, regexes can be useful for detecting IP addresses in a larger string:

ip_candidates = re.findall(r"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b", ip)

Here, the \b word boundary anchors make sure that the digits don't exceed 3 for each segment.

Using a RegEx to match IP addresses

You have to modify your regex in the following way

pat = re.compile("^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$")

that's because . is a wildcard that stands for "every character"

How to check a part of string with regex pattern in python

import re

regex = "(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.( \
25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.( \
25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.( \
25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)"

result = re.search(regex, "http://110.234.52.124/paypal.com")

you just need remove ^ and $ and call this function
if result is None that means not found

How can I find an IP address in a long string with REGEX?

import re

secv = "90.123.1.100 akmfiawnmgisa gisamgisamgsagr[sao l321r1m r2p4 2342po4k2m4 22.33.4.aer 1.2.3.5344 99.99.99.100 asoifinagf sadgsangidsng sg 13.18.19.100 1.2.3.4"

b = re.findall(r"(?:\s|\A)(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(?=\s|\Z)",secv)

b = list(filter(lambda x: all([int(y) <= 255 for y in x.split('.')]), b))

print(b)

To make it more interesting I added IP addresses at the beginning and end of your string. I am assuming that the ip address needs to be separated by white space on both sides if not at the beginning or end of the string. So I added to the REGEX at the beginning a non-capturing group (?:\s|\A) that will match either a white space character or the beginning of the string. I have also added to the end of the REGEX a lookahead assertion (?=\s|\Z) that will match a single white space character or the end of the line without consuming any characters. The above prints out:

['90.123.1.100', '99.99.99.100', '13.18.19.100', '1.2.3.4']

Regexp to check if an IP is valid

You need to check the allowed numbers in each position. For the first optional digit, acceptable values are 0-2. For the second, 0-5 (if the first digit for that part is present, otherwise 0-9), and 0-9 for the third.

I found this annotated example at http://www.regular-expressions.info/regexbuddy/ipaccurate.html :

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


Related Topics



Leave a reply



Submit