问题描述
在匹配跨越多行的文本时,我在使用 Python 正则表达式时遇到了一些麻烦.示例文本为 ('' 是换行符)
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 ('' is a newline)
some Varying TEXT
DSJFKDAFJKDAFJDSAKFJADSFLKDLAFKDSAF
[more of the above, ending with a newline]
[yep, there is a variable number of lines here]
(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"(^[^>][ws]+)$", 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"^(.+)
((?:
.+)+)", 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.
还要注意,换行符可以由换行符 ()、回车符 (
) 或回车符+组成换行符 (
).如果您不确定您的目标文本是否仅使用换行符,您应该使用这个更具包容性的正则表达式版本:
Be aware, too, that a newline can consist of a linefeed (), a carriage-return (
), or a carriage-return+linefeed (
). 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"^(.+)(?:
|
?)((?:(?:
|
?).+)+)", 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.
这篇关于匹配多行文本块的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!