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 year with Python Regex?
- How to match a YYYY-MM-DD date with Python Regex?
- How to match a URL path using Python regex?
- How to use word boundaries in Python Regex?
- How to replace all using Python regex?
- How to replace using Python regex?
- How to match a hex number with regex in Python?
- How to get all matches from a regex in Python?
- How to perform a zero length match with Python Regex?
- How to get a group from a regex in Python?
See more codes...