python-regexHow to validate an IP using Python regex?
Python regex can be used to validate an IP address. The following example code block uses regex to validate an IP address:
import re
def validate_ip(ip):
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]?)'''
if(re.search(regex, ip)):
print("Valid IP")
else:
print("Invalid IP")
ip = "192.168.1.1"
validate_ip(ip)
The output of the example code is:
Valid IP
Code explanation
import re
: This imports there
module which provides regular expression matching operations.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]?)'''
: This defines the regex pattern which is used to validate the IP address.if(re.search(regex, ip)):
: This uses there.search()
method to search for the regex pattern in the given IP address.print("Valid IP")
: This prints the output if the IP address is valid.print("Invalid IP")
: This prints the output if the IP address is invalid.
Helpful links
More of Python Regex
- How to match a YYYY-MM-DD date with Python Regex?
- How to match a year with Python Regex?
- How to use word boundaries in Python Regex?
- How to ignore case in Python regex?
- How to match HTML tags with regex in Python?
- How to match whitespace in Python regex?
- How to replace all using Python regex?
- How to match a hex number with regex in Python?
- How to match a UUID using Python regex?
- How to match a URL path using Python regex?
See more codes...