首页 > 解决方案 > 如何从正则表达式查找所有函数中获取第一个匹配项?

问题描述

我是 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

标签: python-3.xregexlistoutput

解决方案


如果您的预期匹配跨越多行,我建议将文件作为单个字符串读入内存。您可以通过将其替换为来修复代码

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+ 换行符之后的任何一个或多个数字。


推荐阅读