正则表达式匹配多行文本块 [英] Regular expression matching a multiline block of text
问题描述
在与跨多行的文本进行匹配时,让Python正则表达式工作很麻烦.示例文本为("\ n"是换行符)
I'm having a bit of trouble getting a Python regex to work when matching against text that spans multiple lines. The example text is ('\n' is a newline)
some Varying TEXT\n
\n
DSJFKDAFJKDAFJDSAKFJADSFLKDLAFKDSAF\n
[more of the above, ending with a newline]\n
[yep, there is a variable number of lines here]\n
\n
(repeat the above a few hundred times).
我想捕获两件事情:"some_Varying_TEXT"部分,以及一次捕获中位于其下方两行的所有大写文本行(我以后可以去除换行符). 我尝试了几种方法:
I'd like to capture two things: the 'some_Varying_TEXT' part, and all of the lines of uppercase text that comes two lines below it in one capture (i can strip out the newline characters later). I've tried with a few approaches:
re.compile(r"^>(\w+)$$([.$]+)^$", re.MULTILINE) # try to capture both parts
re.compile(r"(^[^>][\w\s]+)$", re.MULTILINE|re.DOTALL) # just textlines
及其许多变体,没有运气.最后一个似乎与文本行一一对应,这不是我真正想要的.我可以抓住第一部分,没问题,但是我似乎无法抓住4-5行的大写文本. 我希望match.group(1)是some_Varying_Text,group(2)是line1 + line2 + line3 + etc,直到遇到空行.
and a lot of variations hereof with no luck. The last one seems to match the lines of text one by one, which is not what I really want. I can catch the first part, no problem, but I can't seem to catch the 4-5 lines of uppercase text. I'd like match.group(1) to be some_Varying_Text and group(2) to be line1+line2+line3+etc until the empty line is encountered.
如果有人好奇,它应该是构成蛋白质的氨基酸序列.
If anyone's curious, its supposed to be a sequence of aminoacids that make up a protein.
推荐答案
尝试一下:
re.compile(r"^(.+)\n((?:\n.+)+)", re.MULTILINE)
我认为您的最大问题是您期望^
和$
锚点与换行符匹配,但它们不匹配.在多行模式下,^
紧跟在换行之后 的位置,而$
匹配紧接换行在之前的位置.
I think your biggest problem is that you're expecting the ^
and $
anchors to match linefeeds, but they don't. In multiline mode, ^
matches the position immediately following a newline and $
matches the position immediately preceding a newline.
也要注意,换行符可以由换行符(\ n),回车符(\ r)或回车符+换行符(\ r \ n)组成.如果不确定目标文本仅使用换行符,则应使用此包含更多内容的正则表达式:
Be aware, too, that a newline can consist of a linefeed (\n), a carriage-return (\r), or a carriage-return+linefeed (\r\n). If you aren't certain that your target text uses only linefeeds, you should use this more inclusive version of the regex:
re.compile(r"^(.+)(?:\n|\r\n?)((?:(?:\n|\r\n?).+)+)", re.MULTILINE)
顺便说一句,您不想在这里使用DOTALL修饰符;您所依赖的事实是,点匹配所有 换行符.
BTW, you don't want to use the DOTALL modifier here; you're relying on the fact that the dot matches everything except newlines.
这篇关于正则表达式匹配多行文本块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!