首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >匹配多行文本块的正则表达式

匹配多行文本块的正则表达式
EN

Stack Overflow用户
提问于 2009-02-25 19:00:50
回答 3查看 320.5K关注 0票数 131

在匹配跨越多行的文本时,我在使用Python正则表达式时遇到了一些问题。示例文本为('\n‘是换行符)

代码语言:javascript
复制
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”部分,以及在一次捕获中出现在它下面两行的所有大写文本行(稍后我可以去掉换行符)。我尝试了几种方法:

代码语言:javascript
复制
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,line1+line2+line3+etc (2)为line1+line2+line3+etc,直到遇到空行。

如果有人好奇的话,它应该是组成蛋白质的一系列氨基酸。

EN

回答 3

Stack Overflow用户

发布于 2018-09-16 02:57:56

以下是与多行文本块匹配的正则表达式:

代码语言:javascript
复制
import re
result = re.findall('(startText)(.+)((?:\n.+)+)(endText)',input)
票数 13
EN

Stack Overflow用户

发布于 2009-02-25 20:59:59

如果每个文件只有一个氨基酸序列,我根本不会使用正则表达式。就像这样:

代码语言:javascript
复制
def read_amino_acid_sequence(path):
    with open(path) as sequence_file:
        title = sequence_file.readline() # read 1st line
        aminoacid_sequence = sequence_file.read() # read the rest

    # some cleanup, if necessary
    title = title.strip() # remove trailing white spaces and newline
    aminoacid_sequence = aminoacid_sequence.replace(" ","").replace("\n","")
    return title, aminoacid_sequence
票数 5
EN

Stack Overflow用户

发布于 2009-02-25 20:58:29

我的偏好。

代码语言:javascript
复制
lineIter= iter(aFile)
for line in lineIter:
    if line.startswith( ">" ):
         someVaryingText= line
         break
assert len( lineIter.next().strip() ) == 0
acids= []
for line in lineIter:
    if len(line.strip()) == 0:
        break
    acids.append( line )

此时,您已经将someVaryingText作为字符串,并将acids作为字符串列表。您可以执行"".join( acids )来生成单个字符串。

我发现这比多行正则表达式不那么令人沮丧(而且更灵活)。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/587345

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档