python-3.x - 如何从正则表达式查找所有函数中获取第一个匹配项?
问题描述
我是 regex 和 python 的新手,我必须从文本文件中找到一个关键字,在成功找到字符串后,我必须从字符串中找到唯一的数字。但是这个数字被打印了 6 次。我只需要将第一个结果作为整数存储在变量中。这是我的完整代码。我从 .txt 文件中查找的字符串是“Lost\n7”。我想从这个字符串中得到的数字是 7。
import re
with open('test.txt') as f:
for line in f:
# Capture one-or-more characters of non-whitespace after the initial match
# rsrp = re.search(r'RSRP:(\S+)', line)
packet_loss_search = re.search(r'Lost(\S+)',line)
# Did we find a match?
if (packet_loss_search):
# Yes, process it
details = packet_loss_search.group(0)
a=str(details)
#a=a[-1]
#print(a)
temp =re.findall(r'\d+', a)
res = list(map(int, temp))
print(res[0])
输出:
7
7
7
7
7
7
解决方案
如果您的预期匹配跨越多行,我建议将文件作为单个字符串读入内存。您可以通过将其替换为来修复代码
import re
with open('test.txt', 'r') as f:
m = re.search(r'Lost\n(\d+)', f.read())
if m: # Check if there is a match
print(m.group(1))
在这里,f.read()
将文件内容读入单个字符串,Lost\n(\d+)
并将匹配并捕获到 Group 1 Lost
+ 换行符之后的任何一个或多个数字。
推荐阅读
- haskell - 如何从嵌套的同义词类型中获取价值
- http - 通过 http 请求远程启动服务
- spring - Spring Boot Admin 多次登录到受保护的 Actuator
- python - Seaborn:线图看起来像阶梯图
- mysql - sequelize 中的嵌套查询
- jquery - 无法禁用下拉列表中的某些特定选项
- javascript - React Native 无法访问 api
- android - 当用户启动一些选定的应用程序时启动我的活动
- sql - 如何获取第一个表的每个 ID 的电子邮件 ID(一个值),然后在 SQL Server 2012 中将第二个表中的电子邮件名称显示为逗号分隔?
- selenium-webdriver - 从命令行运行 webdriver.io 以在 microsoft vsts build 上运行测试