【发布时间】:2020-04-01 16:52:00
【问题描述】:
我正在尝试在 Python 中创建一个Regular-Expression,它应该在多行字符串中捕获与它们对应的标题和文本。示例字符串:
.Main Header
This is the main paragraph in the text. Also this is another sentence.
.Sub-Header
This is secondary header and text.
.Last Header
And this is the last header in the text.
这里.Main Header、.Sub-Header 和.Last Header 是段落的标题,接下来的几行(直到下一个“.Header”字符串的文本)是正文。所以我的预期输出是:
Header1 - .Main Header, Text1 - This is the main paragraph in the text. Also this is another sentence.
Header2 - .Sub-Header, Text2 - This is secondary header and text.
Header3 - .Last Header, Text3 - And this is the last header in the text.
我试图组合一个regex 来满足这个期望,它几乎可以工作,我面临的唯一挑战是捕获一个dot(.) 位于句子之间的文本(例如,Text1),我的regex 的停止标准是newline 和dot(.),因为下一个标题从dot(.) 开始,所以我正在寻求帮助来区分带有换行点的常规点作为我的停止标准。
我目前的正则表达式是:
^(.\w+[^\n]+)\n([^\.]+)
对于Text1,这会捕获:
This is the main paragraph in the text
但应该捕获:
This is the main paragraph in the text. Also this is another sentence.
【问题讨论】:
-
其实没必要用
regex。 -
@jizhihaoSAMA - 我知道,但我想用正则表达式来做,我快到了。
-
也许他们认为你让它变得更复杂?我不知道。
-
也许
^(.\w+[^\n]+)\n(.*?)\.$会从下一行到行尾的最后一个点全部抓取。演示:regex101.com/r/cPk723/1 -
@MDR - 感谢您的帮助,我错过了这个技巧。您应该将此添加为答案,然后我会将这个问题标记为完成。