使用regex编写脚本以打印两个模式之间的字符串,但只打印最后一次出现的字符串

2024-06-16 13:37:48 发布

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

我正在我的raspberrypi3上编写一个python脚本,它将从一个开源的scale记录权重并将它们放入数据库中。电子秤只是将输出/读数记录到一个文件中。问题是电子秤输出了很多我不需要的数据。每次脚本运行时,它都会在文件的底部添加一个新的读数,您可以看到下面的一部分。所以基本上我需要的是最新的重量读数,它总是在文件的最后一行。你知道吗

我对正则表达式有点不在行。尽管我一直在寻找和尝试,但我似乎无法将最后的体重读数分离出来。你知道吗

Serial Load Cell Converter version 1.2
By SparkFun Electronics
No remote sensor found
Minimum time between reports: 791
Press x to bring up settings
Readings:
1274,2.5007,lbs,540611,

Serial Load Cell Converter version 1.2
By SparkFun Electronics
No remote sensor found
Minimum time between reports: 792
Press x to bring up settings
Readings:
1341,2.5008,lbs,540620,

Serial Load Cell Converter version 1.2
By SparkFun Electronics
No remote sensor found
Minimum time between reports: 792
Press x to bring up settings
Readings:
1321,2.5009,lbs,540643,

最后一行: 1321,2.5009,磅,540643

我需要“2.5009”所在的值,但我不能简单地匹配这个数字,因为它会随着每个读数的增加而急剧变化,就像最后一行上的其他数字一样。唯一保持不变的是逗号和“lbs”。你知道吗


Tags: 文件nobyremoteversionserialloadcell
1条回答
网友
1楼 · 发布于 2024-06-16 13:37:48

也许,这个表达式可以提取最后一个值:

.*Readings:\s*[^,]*,\s*([^,]*?)\s*,

测试

import re

regex = r".*Readings:\s*[^,]*,\s*([^,]*?)\s*,"

test_str = """
Serial Load Cell Converter version 1.2
By SparkFun Electronics
No remote sensor found
Minimum time between reports: 791
Press x to bring up settings
Readings:
1274,2.5007,lbs,540611,

Serial Load Cell Converter version 1.2
By SparkFun Electronics
No remote sensor found
Minimum time between reports: 792
Press x to bring up settings
Readings:
1341,2.5008 ,lbs,540620,

Serial Load Cell Converter version 1.2
By SparkFun Electronics
No remote sensor found
Minimum time between reports: 792
Press x to bring up settings
Readings:
1321, 2.5009,lbs,540643,

"""

print(re.findall(regex, test_str, re.DOTALL))

输出

['2.5009']

If you wish to explore/simplify/modify the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


相关问题 更多 >