使用 Python 使用正则表达式从日志文件中提取文件名
Using a regular expression to extract a file name from a logfile using Python
希望创建从日志文件访问的文件列表。文件中的两个字符串示例如下所示。
..... [08/Mar/2020:19:11:15 -0700] "GET /socview/15Ragged.htm HTTP/1.1" 200 6564 .........
..... [08/Mar/2020:19:11:31 -0700] "GET /socview/?C=D;O=A HTTP/1.1" 200 13443 ...............
/socview/15Ragged.htm 是我要提取的内容。以 .htm .log .txt 等结尾
/socview/?C=D;O=A 是我试图避免提取的内容。
好像是“.”是什么导致了问题,因为当我 运行 代码而不搜索它时,即。 运行 下方的 RE 完美地作为此 post.
底部显示的循环的一部分
unique = re.search(r'GET (\S+)', x)
但是它正在提取我不想要的字符串。下面是我正在尝试使用的循环和 RE,这对我来说很有意义,当 运行 显示以下消息时,我无法弄清楚出了什么问题。任何帮助将不胜感激
"if unique.group(1) 不在 unilist:
AttributeError: 'NoneType' 对象没有属性 'group'"
for x in input:
unique = re.search(r'GET (\S+\.\S+)', x)
if unique.group(1) not in unilist:
unilist.append(unique.group(1))
GET (\S+\.\S+)
没问题。问题是 re.search()
returns None
如果匹配失败,那么对于你提供的第二个字符串 unique
是 None
没有group
属性.
尝试以下操作:
for x in input:
unique = re.search(r'GET (\S+\.\S+)', x)
if unique is None:
continue
if unique.group(1) not in unilist:
unilist.append(unique.group(1))
我建议您使用更好的变量名。例如 input
是 Python 中的一个内建函数,避免隐藏它。如果循环体增长,将很难遵循 x
.
这样的名称
此外,我建议像这样预编译正则表达式,否则它会在每个循环中编译它,这非常耗时:
matcher = re.compile("GET (\S+\.\S+)")
for line in lines:
# your loop body here
希望创建从日志文件访问的文件列表。文件中的两个字符串示例如下所示。
..... [08/Mar/2020:19:11:15 -0700] "GET /socview/15Ragged.htm HTTP/1.1" 200 6564 .........
..... [08/Mar/2020:19:11:31 -0700] "GET /socview/?C=D;O=A HTTP/1.1" 200 13443 ...............
/socview/15Ragged.htm 是我要提取的内容。以 .htm .log .txt 等结尾
/socview/?C=D;O=A 是我试图避免提取的内容。
好像是“.”是什么导致了问题,因为当我 运行 代码而不搜索它时,即。 运行 下方的 RE 完美地作为此 post.
底部显示的循环的一部分unique = re.search(r'GET (\S+)', x)
但是它正在提取我不想要的字符串。下面是我正在尝试使用的循环和 RE,这对我来说很有意义,当 运行 显示以下消息时,我无法弄清楚出了什么问题。任何帮助将不胜感激
"if unique.group(1) 不在 unilist:
AttributeError: 'NoneType' 对象没有属性 'group'"
for x in input:
unique = re.search(r'GET (\S+\.\S+)', x)
if unique.group(1) not in unilist:
unilist.append(unique.group(1))
GET (\S+\.\S+)
没问题。问题是 re.search()
returns None
如果匹配失败,那么对于你提供的第二个字符串 unique
是 None
没有group
属性.
尝试以下操作:
for x in input:
unique = re.search(r'GET (\S+\.\S+)', x)
if unique is None:
continue
if unique.group(1) not in unilist:
unilist.append(unique.group(1))
我建议您使用更好的变量名。例如 input
是 Python 中的一个内建函数,避免隐藏它。如果循环体增长,将很难遵循 x
.
此外,我建议像这样预编译正则表达式,否则它会在每个循环中编译它,这非常耗时:
matcher = re.compile("GET (\S+\.\S+)")
for line in lines:
# your loop body here