Python正则表达式获取字符串正确,但仍有AttributeE

2024-04-24 22:41:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我想通过regex从vsftp日志中获取ftp帐户信息。 我们所有的帐户都是由用户加上数字命名的,比如user01,user02,user03

Tue Sep 12 18:11:20 2017 1 ::ffff:172.18.1.168 3620 /ftptest.py a _ i r user01 ftp 0 * c
Tue Sep 12 18:12:51 2017 1 ::ffff:172.18.1.168 4211 /ftptest.py a _ i r user02 ftp 0 * c
Tue Sep 12 18:16:43 2017 1 ::ffff:172.18.1.168 4322 /ftptest.py a _ i r user03 ftp 0 * c

我的代码如下:

#!/usr/bin/python
import re


with open("/var/log/xferlog") as ftplog:
    for line in ftplog:
        line = line.strip("\n")
        pattern = re.compile(r'user[\d]+')
        match = pattern.search(line)
        print match.group()

结果可以获取用户帐户,但也会显示错误消息AttributeError:“NoneType”对象没有属性“group”

结果是:

user01
user02
user03
Traceback (most recent call last):
  File "test8.py", line 10, in <module>
    print match.group()
AttributeError: 'NoneType' object has no attribute 'group'

谁能给我一些建议吗


Tags: 用户pyrematchlinegroupftp帐户
3条回答

使用if语句处理模式不匹配的情况

...
if match:
    print match.group()  # or anything

但请注意,这将使所有不匹配的情况保持沉默。如果您想跟踪这些(也许是为了调试),您可以添加

else:
    print line

我无法根据您的示例数据和代码让user01、user02、user03打印,但看起来您的regex没有正确捕获值。为了帮助您排除故障,我建议使用Python debugger来帮助您遍历代码:

#!/usr/bin/python
import re


with open("sample") as ftplog:
    for line in ftplog:
        line = line.strip("\n")
        pattern = re.compile(r'sparq[\d]+')
        match = pattern.search(line)
        if match is None:
            import pdb; pdb.set_trace()
        print match.group()

pattern.search(line)如果与line不匹配,则返回None。 所以你的代码必须添加一个条件

#!/usr/bin/python
import re
with open("/var/log/xferlog") as ftplog:
    for line in ftplog:
        line = line.strip("\n")
        pattern = re.compile(r'user[\d]+')
        match = pattern.search(line)
        if match:
           print match.group()

向尤恩问好

相关问题 更多 >