繁体   English   中英

正则表达式提取段落基于 2 正则表达式匹配

[英]Regex extract paragraph based on 2 regex match

我正在开发一个 python 自动化脚本,我想根据正则表达式匹配提取特定段落,但我被困在如何提取段落上。 以下是显示我的案例的示例:

解决方案:(一致模式)

我要提取的段落(Inconsistent Pattern)

远程值:x(一致模式)

以下是我目前正在做的程序,如果有人能指教我就太好了!

import re
test= 'Solution\s:'
test1='Remote'
with open('<filepath>', 'r') as extract:
            
            lines=extract.readlines()

            for line in lines:
                x = re.search(test, line)
                y = re.search(test1, line)
                if x is not y:
                    f4.write(line)
                    print('good')
                else:
                    print('stop')

这可以使用正则表达式轻松完成,例如:

import re

text = r"""
Solution\s:
The paragraph I
want to extract
Remote
Some useless text here
Solution\s:
Another paragraph
I want to
extract
Remote

"""
m = re.findall(r"Solution\\s:(.*?)Remote", text, re.DOTALL | re.IGNORECASE)
print(m)

其中text表示一些感兴趣的文本(例如从文件中读取),我们希望从中提取标记模式Solution\\s:Remote之间的所有部分。 在这里,我们使用 IGNORECASE 搜索,以便即使拼写不同的大小写也能识别哨兵模式。

上面的代码输出:

['\nThe paragraph I\nwant to extract\n', '\nAnother paragraph\nI want to\nextract\n']

有关更多详细信息,阅读https://docs.python.org/3/library/re.html 上的 Python re 库文档。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM