我正在使用 python 逐行搜索文本日志文件,我想将一行的特定部分保存为变量。我正在使用 Regex,但我认为我没有正确使用它,因为我的变量 string_I_want 总是得到 None。我在这里查看其他 Regex 问题,看到人们将 .group() 添加到他们的 re.search 末尾,但这给了我一个错误。我不是最熟悉 Regex 的人,但不知道我哪里出错了?
示例日志文件:
2016-03-08 11:23:25 test_data:0317: m=string_I_want max_count: 17655, avg_size: 320, avg_rate: 165
我的脚本:
def get_data(log_file):
#Read file line by line
with open(log_file) as f:
f = f.readlines()
for line in f:
date = line[0:10]
time = line[11:19]
string_I_want=re.search(r'/m=\w*/g',line)
print date, time, string_I_want
请您参考如下方法:
您需要删除带有全局标志的 /.../ 分隔符,并使用捕获组:
mObj = re.search(r'm=(\w+)',line)
if mObj:
string_I_want = mObj.group(1)
查看此 regex demo和 Python demo :
import re
p = r'm=(\w+)' # Init the regex with a raw string literal (so, no need to use \\w, just \w is enough)
s = "2016-03-08 11:23:25 test_data:0317: m=string_I_want max_count: 17655, avg_size: 320, avg_rate: 165"
mObj = re.search(p, s) # Execute a regex-based search
if mObj: # Check if we got a match
print(mObj.group(1)) # DEMO: Print the Group 1 value
图案细节:
m=- 匹配m=文字字符序列(如果必须匹配整个单词,则在之前添加空格或\b)(\w+)- 第 1 组捕获 1+ 个字母数字或下划线字符。我们可以使用.group(1)方法引用此值。
