解决方法没有从正则表达式搜索中读取变量

Workaround no Variable Read in From Regex Search

我试图打印出从 regex 表达式中读入的字符串。对于使用我的正则表达式搜索读入的某些文本行,没有数据,因此没有任何可读入的内容。发生这种情况时,我得到错误 "AttributeError: 'NoneType' object has no attribute 'group'。谁能帮我在我的代码中写一个解决方法,这样当从正则表达式搜索中没有读入任何内容时,变量就不会被打印出来?我试过 if (col3.group() != None):,但这似乎不起作用。

#!/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

一个常见的模式是:

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

你的情况:

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

或者,这里有一个示例,说明如何遍历所有匹配项并在没有匹配项时设置默认的空字符串值:

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

顺便说一句,这里有一个关于如何以安全和快捷的方式提取捕获组的相关线程:

  • Getting captured group in one line

您需要检查 col3col4 是否是 None,而不是组:

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

而不是这个:

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

这样做:

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