python - 正则表达式读取文件并在 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
解决方案
您可以使用
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
笔记
正\d+(?:[.-]\w+)*\s*(\S.*)?$
则表达式搜索 1+ 个数字,然后搜索 0 个或多个重复.
或-
后跟 1+ 个单词字符,然后尝试匹配 0+ 个空格,然后将任何非空格字符捕获到第 1 组中,然后是任何 0+ 个字符,直到行结束。如果组 1 不为空,则找到匹配项并break
停止处理。
否则,found
布尔标志设置为True
并返回下一个非空行。
推荐阅读
- oauth-2.0 - Auth2 + Open ID Connect,如何使用内部后端进行授权?
- reactjs - 使用单元格度量呈现占位符时,网格行高度未计算正确的高度
- magento - Magento 2 在导出订单时崩溃
- javascript - 表格中的jQuery过滤器元素
- amazon-web-services - AWS CloudFormation NestedStacks 与模块
- authentication - 为什么我收到错误 500“出了点问题!” 使用 Azure DevOPS 登录时(请求“/v1/Authorizations/vso”)
- javascript - 如何将对象映射到ui?
- django - Django Rest Framework 中的循环操作
- flutter - Dismissible 容器和 ListView 项大小不同
- javascript - 如何在 javascript/react js 中制作动画?