首页 > 解决方案 > 正则表达式读取文件并在 Python 中从文件内部返回匹配模式之后的第一行

问题描述

示例字符串 1:

7.2.P.8.1 

Summary and Conclusion  


A stability study with two batches was carried out.

示例字符串 2:

7.2.S.1.2  

Structure 

Not applicable as the substance is not present.

我想编写一个正则表达式来获取此表单 (7.2.P.8.1 ) 或 (7.2.S.1.2 ) 或 (8-3-1-P-2) 或任何其他格式之后的第一行(所有内容都将是用 . 或 -) 分隔并检索它。所以从我需要的第一个实例作为输出(摘要和结论)和第二个实例(结构)。“示例字符串”一词不会成为文件内容的一部分,仅用于显示示例。

也许偶尔格式会像:

9.2.P.8.1 Summary and Conclusion  

A stability study with two batches was carried out. 

在这种情况下,我也想检索输出:摘要和结论

注意:我只想从文件中检索第一个匹配模式而不是所有匹配项,因此我的代码在找到第一个匹配模式后应该会中断。我怎样才能有效地做到这一点。

到目前为止的代码:

import re
def func():
    with open('/path/to/file.txt') as f: # Open the file (auto-close it too)
        for line in f: # Go through the lines one at a time
            m = re.match('\d+(?:[.-]\w+)*\s*', line) # Check each line
            if m: # If we have a match...
                return m.group(1) # ...return the value

标签: pythonregex

解决方案


您可以使用

import re

rx = re.compile(r'\d+(?:[.-]\w+)*\s*(\S.*)?$')
found = False
with open('/path/to/file.txt', 'r') as f:
    for line in f:
        if not found:                         # If the required line is not found yet
            m = rx.match(line.strip())        # Check if matching line found
            if m:                               
                if m.group(1):                # If Group 1 is not empty 
                    print(m.group(1))         # Print it
                    break                     # Stop processing
                else:                         # Else, the next blank line is necessary
                    found=True                # Set found flag to True
        else:
            if not line.strip():              # Skip blank line
                pass
            else:
                print(line.strip())           # Else, print the match
                break                         # Stop processing

请参阅Python 演示正则表达式演示

笔记

\d+(?:[.-]\w+)*\s*(\S.*)?$则表达式搜索 1+ 个数字,然后搜索 0 个或多个重复.-后跟 1+ 个单词字符,然后尝试匹配 0+ 个空格,然后将任何非空格字符捕获到第 1 组中,然后是任何 0+ 个字符,直到行结束。如果组 1 不为空,则找到匹配项并break停止处理。

否则,found布尔标志设置为True并返回下一个非空行。


推荐阅读