如何使用重新匹配() ?

2024-10-03 11:18:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我对文本条目应用了许多regex模式,我希望它们能自动输入到一个列表中。你知道吗

例如

import re
raw='NIH05484225_1_binders_list ID_054345 Proteincomplex /D1/ERBH1_ERV_ACWX'

regex= '.*Proteincomplex /[\S]+\/([\S]+)_([\S]+)_([\S]+)'
regex=re.compile(regex)


result = re.match(regex, raw)
answer=[]
answer.append (result.group(1))
answer.append (result.group(2))
answer.append (result.group(3))

print (answer)

有没有办法让answer收集所有捕获的结果? 如在

answer.extend (result.allgroups()) # does not work, of course


Tags: answer文本importre列表raw模式group
1条回答
网友
1楼 · 发布于 2024-10-03 11:18:02

您可以使用^{}

Return a tuple containing all the subgroups of the match, from 1 up to however many groups are in the pattern. The default argument is used for groups that did not participate in the match; it defaults to None.

因此,您可以这样修改代码:

import re
raw='NIH05484225_1_binders_list ID_054345 Proteincomplex /D1/ERBH1_ERV_ACWX'
regex=re.compile(r'.*Proteincomplex\s+/\S+\/(\S+)_(\S+)_(\S+)')
result = re.match(regex, raw)
if result:
    print (answer.groups())

注意:您不需要用字符类包装每个\S,使用\s+而不是空格可以匹配任何一个或多个空格(它被认为更可读且故障安全,特别是如果您计划稍后使用re.VERBOSE/re.X在模式中插入注释或格式化空格)。你知道吗

相关问题 更多 >