find ipv4 addresses in a string using regex in python

To find IPv4 addresses in a string using regex in Python, we can use the re module in Python. We can define a regex pattern to search for IPv4 addresses and use the re module's findall method to find all matches in a given input string.

Here is an example code snippet that demonstrates how to find IPv4 addresses in a string using regex in Python:

main.py
import re

ipv4_pattern = r'\b(?:\d{1,3}\.){3}\d{1,3}\b'

input_string = 'The IP address of the server is 192.168.1.1 and the client IP address is 10.0.0.1.'

ipv4_addresses = re.findall(ipv4_pattern, input_string)

print(ipv4_addresses) # Output: ['192.168.1.1', '10.0.0.1']
276 chars
10 lines

In this example, we define a regex pattern ipv4_pattern that matches IPv4 addresses in the string. The pattern \d{1,3} matches 1-3 digits, and (?:\d{1,3}\.){3} matches this pattern three times followed by a final match of \d{1,3}. The \b at the beginning and end of the pattern specifies that the match must occur at a word boundary.

We then use the re.findall method to find all matches of this pattern in the input string, which gives us a list of IPv4 addresses found in the string.

related categories

gistlibby LogSnag