Regex读取一个文件并返回Python文件中匹配模式后的第一行

2024-04-19 07:50:43 发布

您现在位置: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)或任何其他格式(所有内容都将用分隔符分隔)之后的第一行。或者-)并取回它。所以从一开始 我需要的输入作为输出(摘要和结论)和第二个实例(结构)。“Example String”这个词不会是文件内容的一部分,只是用来展示一个示例。你知道吗

也许偶尔格式会像:

9.2.P.8.1 Summary and Conclusion  

A stability study with two batches was carried out. 

在本例中,我还希望检索为输出:Summary和Conclusion

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

迄今为止的代码:

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

Tags: andthe字符串示例withline模式batches
1条回答
网友
1楼 · 发布于 2024-04-19 07:50:43

你可以用

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 demoregex demo。你知道吗

注意事项

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

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

相关问题 更多 >