python-regexHow to match an IP address with regex in Python?
Regex (Regular Expression) is a powerful tool for matching patterns in strings. In Python, it can be used to match an IP address with the re
module.
Example code
import re
# Sample IP address
ip = "10.10.10.1"
# Regex for IP address
regex = '''
^ # Start of the line
(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?) # First number (0-255)
\. # Dot
(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?) # Second number (0-255)
\. # Dot
(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?) # Third number (0-255)
\. # Dot
(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?) # Fourth number (0-255)
$ # End of the line
'''
# Compile the Regex
pattern = re.compile(regex)
# Match the IP address
match = pattern.match(ip)
# Print the match
print(match)
Output example
<re.Match object; span=(0, 11), match='10.10.10.1'>
The code above uses the re
module to compile a regex pattern for matching an IP address. The regex pattern consists of four parts, each representing a number from 0 to 255. The pattern is then used to match the IP address, and the result is printed.
Code explanation
^
: Start of the line(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)
: First number (0-255)\.
: Dot(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)
: Second number (0-255)\.
: Dot(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)
: Third number (0-255)\.
: Dot(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)
: Fourth number (0-255)$
: End of the line
Helpful links
More of Python Regex
- How to match a YYYY-MM-DD date with Python Regex?
- How to use word boundaries in Python Regex?
- How to match a URL path using Python regex?
- How to perform a zero length match with Python Regex?
- How to match a UUID using Python regex?
- How to match a year with Python Regex?
- How to match a URL using Python regex?
- How to remove numbers from a string using Python regex?
- How to replace all using Python regex?
- How to get all matches from a regex in Python?
See more codes...