Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to extract all IP addresses from a file using Python

noob here.

I’m trying to extract all IP addresses from a file where the IP addresses are all in random positions, with there sometimes being more than one IP on a line. It’s a text file with the contents looking like the below:

hello9.9.9.9                     hdi3ohdoi3hoi3oid2         10.3.2.3            2.3.4.5
ddjeijfdeio
eifhoehjwiehfiowe
uiewhduihewiudhue
8.8.8.8, 20.20.20.20
de2hd9j39ud9829d8 192.168.10.24

My code only returns the first ip address on each line,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

['9.9.9.9', '8.8.8.8', '192.168.10.24']

My code is below:


with open('C:/testfile.txt') as fh:
    file = fh.readlines()

pattern = re.compile(r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})')

lst = []

for line in file:
    match = pattern.search(line)
    if match is not None:
        lst.append(match[0])

print(lst)

Any ideas how I can list all the IP’s?

Thanks in advance

J

>Solution :

You can use re.findall for that:

import re

data = """
hello9.9.9.9                     hdi3ohdoi3hoi3oid2         10.3.2.3            2.3.4.5
ddjeijfdeio
eifhoehjwiehfiowe
uiewhduihewiudhue
8.8.8.8, 20.20.20.20
de2hd9j39ud9829d8 192.168.10.24
"""

result = re.findall(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', data)
print(result)

Result:

['9.9.9.9', '10.3.2.3', '2.3.4.5', '8.8.8.8', '20.20.20.20', '192.168.10.24']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading