samedi 18 juin 2016

Python Regex: How to append string if found and append "Not Found" otherwise?

I am trying to append a result to a list if found, and append the string "N/A" to the list if no match is found. show_version_lists is a list of logs from various network devices.

import re

for result in show_version_list:

    for matchedtext in re.findall(r'(?<=Version).*?(?=-)',result)[:1]:

        if re.search(r'(?<=Version).*?(?=-)',result):

            version_numbers_xe.append(matchedtext)

        else:

            version_numbers_xe.append('n/a')

When I run the above code the else condition never occurs.

An Example of one of the logs that should match

Load for five secs: 5%/0%; one minute: 4%; five minutes: 4%
Time source is NTP, 15:24:47.756 PDT Thu Jun 16 2016
Cisco IOS XE Software, Version 03.16.01a.S - Extended Support Release
Cisco IOS Software, ASR1000 Software (PPC_LINUX_IOSD-ADVENTERPRISEK9-M), Version 15.5(3)S1a, RELEASE SOFTWARE (fc1)
Technical Support: http://www.cisco.com/techsupport
Copyright (c) 1986-2015 by Cisco Systems, Inc.
Compiled Wed 04-Nov-15 17:40 by mcpre

An Example of one of the logs that shouldn't match.

Cisco IOS Software, C3750E Software (C3750E-UNIVERSALK9-M), Version   15.2(2)E3, RELEASE SOFTWARE (fc3)
Technical Support: http://www.cisco.com/techsupport
Copyright (c) 1986-2015 by Cisco Systems, Inc.
Compiled Wed 26-Aug-15 06:14 by prod_rel_team

Edit:

AChampion you were right taking out the for loop fixed the problem. I feel silly!

for result in show_version_list:

    if re.search(r'(?<=Version).*?(?=-)',result):

        version_numbers_xe.append(matchedtext)
    else:
        na = 'n/a'
        version_numbers_xe.append(na)

Aucun commentaire:

Enregistrer un commentaire