I want to match a newline character followed by a string using regular expression in python

Device ID: xyz
Entry address(es): 
 IP address:
Platform: WS-x,  Capabilities: Switch IGMP 
Interface: GigabitEthernet9/33,  Port ID (outgoing port): GigabitEthernet0/2
Holdtime : 177 sec
Management address(es): 
 IP address:

above is a snipet from a file.From among the above i want to collect the ip address by matching only the 2 lines below. Entry address(es): IP address: or Management address(es): IP address:

The regular expression i have written is as follows which does not work and i am not able to resolve how i can show the new line after "address(es):" in my regular expression.

f = open(fileName)
for line in f:
    matchObj1 = re.match(r'Entry address\(es\):\s+IP address: ([0-9.]+)', line)
    if matchObj1:
    print "IP Address = ", matchObj1.group(1)

    matchObj2 = re.match(r'Entry address\(es\):\s+IP address: ([0-9.]+)', line)
    if matchObj2:
    print "IP Address = ", matchObj2.group(1)

Please Help. Thank you.


You don't need to use regular expressions for this. Your input looks like the output of a configuration file or a program, and easy to parse.

def get_addresses(fname):
    addresses = {}
    with open(fname) as f:
        lines = [l.strip().lower() for l in f]

    for i, line in enumerate(lines):
        if line.startswith("ip address"):
            ip = line.split(": ")[1]
            address_type = lines[i-1]
            if address_type == "entry address(es):":
                addresses["entry"] = ip
            elif address_type == "management address(es):":
                addresses["management"] = ip
            # Add additional address type handling here

    return addresses

You need to use re.search instead of re.match, re.match is used for matching from the start of string:

>>> s = 'Device ID: xyz\nEntry address(es): \n      IP address:\n    Platform: WS-x,  Capabilities: Switch IGMP \n    Interface: GigabitEthernet9/33,  Port ID (outgoing port): GigabitEthernet0/2\n    Holdtime : 177 sec'
>>> re.search(r'Entry address\(es\):\s+IP address: ([0-9.]+)', s).group(1)

search() vs. match():

re.match() checks for a match only at the beginning of the string, while re.search() checks for a match anywhere in the string.

Need Your Help

Cannot Clone Bitmap after Stream Disposed

c# directx slimdx

I load a bitmap from a DataStream. I try to return the loaded bitmap from a method, and later use it as a source to clone a new bitmap. Unfortunately, the Clone() call results in an

Sorting å, ä, ö - gets mixed with a / o

php wordpress sorting tags character

Using WordPress and PHP, I'm creating a list of tags on a site sorted by their first character,