pHorseSpec
pHorseSpec

Reputation: 1274

Workaround no Variable Read in From Regex Search

I'm trying to print out strings that are read in from a regex expression. For some of the lines of text being read in with my regex search, there is no data, so there isn't anything to read in. When this occur, I get the error, "AttributeError: 'NoneType' object has no attribute 'group'. Could anyone help me write a work around in my code so that when nothing is read in from the regex search, the variable isn't printed out? I tried if (col3.group() != None):, but that doesn't seem to work.

#!/usr/bin/env python

#purpose of script: To conduct an nslookup on a list of IP addresses

import os, csv, re

#get list of IP's from file
inFile='filesystem/Book1.txt'
ipList = []
with open(inFile, 'rb') as fi:
    for line in fi: 
        line = line.replace(',', '')#remove commas and \n from list
        line = line.replace('\r', '')
        line = line.replace('\n', '')
        ipList.append(line)# create list of IP addresses to lookup

#output results
outFile='filesystem/outFile.txt'
fo = open(outFile, 'w')
inc=0
writeToFileValue = ""
for e in ipList:
    result = os.popen('nslookup ' + e).read()#send nsLookup command to cmd prompt

    col1 = re.search(r'Server:.*', result, re.M|re.I)#use regex to extract data
    col2 = re.search(r'Address:  8.8.8.8', result, re.M|re.I)
    col3 = re.search(r'Name:.*', result, re.M|re.I)
    col4 = re.search(r'Address:  (?!8.8.8.8).*', result, re.M|re.I) 

    print col1.group()
    print col2.group()
    if (col3.group() != None):
        print col3.group() # if none, skip
    if (col4.group() != None):
        print col4.group() # if none, skip

Upvotes: 0

Views: 47

Answers (3)

alecxe
alecxe

Reputation: 473873

A common pattern is:

match = re.search(expression, string, flags)
if match:  # match would be None if there is no match
    print(match.group())

In your case:

col1 = re.search(r'Server:.*', result, re.M|re.I)
if col1:
    print(col1.group())

Or, here is an example, how you can loop over all of the matches and set a default empty string value if there is no match:

matches = [col1, col2, col3, col4]
print([match.group() if match else "" 
       for match in matches]) 

By the way, here is a related thread on how to extract the captured group in a safe and short way:

Upvotes: 1

joel goldstick
joel goldstick

Reputation: 4493

instead of this:

   if (col3.group() != None):
        print col3.group() # if none, skip

do this:

   try col3.group():
        print col3.group()
   except AttributeError:
        pass

Upvotes: 1

zondo
zondo

Reputation: 20336

You need to check if col3 and col4 are None, not the groups:

if (col3 is not None):
    print col3.group()
if (col4.group() is not None):
    print col4.group()

Upvotes: 1

Related Questions