You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用正则表达式从文本文件提取指定时间与带宽值?

问题:用正则表达式提取日志行中的时间与带宽值

目标日志行格式如下:

2022-05-03 11:15:09.395 [6489266] | (rtcp_receiver.cc:823): BwMgr Received a TMMBR with bps: 1751856

目前通过字符串索引(line[12:19]、line[-7:])提取时间(11:15:09)和带宽(1751856),但行内容出现额外字符或空格时就会失效,求合适的正则表达式解决这个问题。

现有代码:

import re
import matplotlib.pyplot as plt
import sys

time =[]
bandwidth = []
myfile = open(sys.argv[1])
for line in myfile:
    line = line.rstrip()
    if re.findall('TMMBR with bps:',line):
        time.append(line[12:19])
        bandwidth.append(line[-7:])

plt.plot(time,bandwidth)
plt.xlabel('time')
plt.ylabel('bandwidth')   
plt.title('TMMBR against time')
plt.legend()
plt.show()

解决方案

可以用一个匹配整行的正则表达式,直接捕获需要的时间和带宽值,不用先判断再提取,一步到位。

修改后的代码:

import re
import matplotlib.pyplot as plt
import sys

time =[]
bandwidth = []
# 定义正则表达式,捕获时间和带宽
pattern = r'\d{4}-\d{2}-\d{2} (\d{2}:\d{2}:\d{2})\.\d+ .*TMMBR with bps: (\d+)'

with open(sys.argv[1]) as myfile:  # 用with语句自动关闭文件,更安全
    for line in myfile:
        match = re.search(pattern, line)
        if match:
            time_str = match.group(1)
            bw_str = match.group(2)
            time.append(time_str)
            bandwidth.append(int(bw_str))  # 转成整数,绘图更合理

plt.plot(time, bandwidth)
plt.xlabel('time')
plt.ylabel('bandwidth')   
plt.title('TMMBR against time')
plt.legend()
plt.show()

正则表达式说明:

  • \d{4}-\d{2}-\d{2}:匹配日志开头的日期部分(如2022-05-03)
  • (\d{2}:\d{2}:\d{2}):捕获目标时间(11:15:09),括号表示分组,后续用group(1)获取该值
  • \.\d+:匹配时间后的毫秒部分(.395),无需捕获
  • .*:匹配中间任意内容,不管行中间有多少字符或空格,都能跳过
  • TMMBR with bps::匹配固定标识,确保只处理目标行
  • (\d+):捕获带宽数值(1751856),用group(2)获取该值

这样不管行中间的内容如何变化,只要日期、时间格式和末尾的带宽标识不变,就能准确提取到需要的值,不会因为额外字符或空格出错。


内容的提问来源于stack exchange,提问作者Sachin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 21:10:18