Home ยป Validate an IP address using ReGex

Validate an IP address using ReGex

Spring Framework Basics Video Course
Java SE 11 Programmer I [1Z0-815] Practice Tests
Oracle Java Certification
1 Year Subscription
Java SE 11 Programmer II [1Z0-816] Practice Tests
Java SE 11 Developer (Upgrade) [1Z0-817]

In this example we will use regular expressions in python to check for a valid IP address

This example will check IPv4 and IPv6 address formats

Table of Contents

Code

# Validate IP addresses using Regex
import re
 
# Function for Validating IP
 
 
def validateIP(IP):
 
    # Regex expression for validating IPv4
    regexIP4 = "^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$"
 
    # Regex expression for validating IPv6
    regexIP6 = "((([0-9a-fA-F]){1,4})\\:){7}"\
             "([0-9a-fA-F]){1,4}"
 
    isIP4 = re.compile(regexIP4)
    isIP6 = re.compile(regexIP6)
 
    # Checking if it is a valid IPv4 addresses
    if (re.search(isIP4, IP)):
        return "This is a valid IPv4"
 
    # Checking if it is a valid IPv6 addresses
    elif (re.search(isIP6, IP)):
        return "This is a valid IPv6"
 
    # Return Invalid
    return "This is an invalid IP"
 
# Driver Code
 
# IP addresses to validate
IP = "127.0.0.1"
print(validateIP(IP))

IP = "201.23.120.21"
print(validateIP(IP))
 
IP = "2001:db8:85a3:8d3:1319:8a2e:370:7348"
print(validateIP(IP))
 
IP = "This.is.an.ip"
print(validateIP(IP))

When you run this you should see something like this

>>> %Run regexip.py
This is a valid IPv4
This is a valid IPv4
This is a valid IPv6
This is an invalid IP

Link

 

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More