Python:使用正则表达式获取文件行中的特定文本
问题描述:
我正在使用python逐行搜索文本日志文件,并且我想将行的某个部分保存为变量。我使用正则表达式,但不认为我正确使用它,因为我总是得到None
为我的变量string_I_want
。我在看这里的其他正则表达式问题,看到人们在其re.search
的末尾添加了.group()
,但是这给了我一个错误。我不是最熟悉正则表达式,但不知道我哪里错了?Python:使用正则表达式获取文件行中的特定文本
日志文件示例:
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)
方法来引用此值。
答
务必:
(?<=\sm=)\S+
例子:
In [135]: s = '2016-03-08 11:23:25 test_data:0317: m=string_I_want max_count: 17655, avg_size: 320, avg_rate: 165'
In [136]: re.search(r'(?<=\sm=)\S+', s).group()
Out[136]: 'string_I_want'
答
这里是你需要的东西:
import re
def get_data(logfile):
f = open(logfile,"r")
for line in f.readlines():
s_i_w = re.search(r'(?<=\sm=)\S+', line).group()
if s_i_w:
print s_i_w
f.close()
正则表达式是wrong..you使用正则表达式的格式的Javascript – rock321987
不要只是猜测那些're'函数和方法做---阅读“[正则表达式HOWTO]”(https://docs.python.org/2/howto/regex.html)“的全面介绍在Python 2中使用正则表达式,并参考['re'参考文档](https://docs.python.org/2/library/re.html)当你需要查询细节。从长远来看,这会节省您的时间。 –