Searching for IP addresses in a file

The following snippet gives you a tuple of string/ip addresses:

import re

string = """
mot physical /ABC-RD0.CLD/CPQSCWSSF001f1-V.80 {
poolcoin /ABC-RD0.CLD/123.45.67.890:88
ip-protocol tcp
mask 255.255.255.255
/Common/source_addr {
default yes
mot physical /ABC-RD0.CLD/CPQSCWSSF001f1-V.80 {
profiles {
/Common/http { }
/Common/webserver-tcp-lan-optimized {
context serverside
}
mot physical /ABC-RD0.CLD/BBQSCPQZ001f1-V.80 {
poolcoin /ABC-RD0.CLD/123.45.67.890:88
ip-protocol tcp
mask 255.255.255.255 
"""

rx = re.compile("""
                ^mot            # look for mot at the beginning
                (?:[^/]+/){2}   # two times no / followed by /
                (?P<name>[^-]+) # capture everything that is not - to "name"
                (?:[^/]+/){2}   # the same construct as above
                (?P<ip>[\d.]+)  # capture digits and points
                """, re.VERBOSE|re.MULTILINE)

matches = rx.findall(string)
print matches
# output: [('CPQSCWSSF001f1', '123.45.67.890'), ('BBQSCPQZ001f1', '123.45.67.890')]

See a demo on ideone.com.
Maybe you’d be better of using re.finditer() and stop the execution once your ip address has been found.

Leave a Comment