python正则表达式。在模式之间提取文本

时间:2012-10-02 14:49:48

标签: python regex

如何获取下面'str'中'uniprotkb:'和'(基因名称)'之间的所有值:

str = 'uniprotkb:HIST1H3D(gene name)|uniprotkb:HIST1H3A(gene name)|uniprotkb:HIST1H3B(gene name)|uniprotkb:HIST1H3C(gene name)|uniprotkb:HIST1H3E(gene name)|uniprotkb:HIST1H3F(gene name)|uniprotkb:HIST1H3G(gene name)|uniprotkb:HIST1H3H(gene name)|uniprotkb:HIST1H3I(gene name)|uniprotkb:HIST1H3J(gene name)' 

结果是:

HIST1H3D
HIST1H3A
HIST1H3B
HIST1H3C
HIST1H3E
HIST1H3F
HIST1H3G
HIST1H3H
HIST1H3I
HIST1H3J 

3 个答案:

答案 0 :(得分:8)

使用re.findall(),您可以获得与正则表达式匹配的字符串的所有部分:

>>> import re
>>> sstr = 'uniprotkb:HIST1H3D(gene name)|uniprotkb:HIST1H3A(gene name)|uniprotkb:HIST1H3B(gene name)|uniprotkb:HIST1H3C(gene name)|uniprotkb:HIST1H3E(gene name)|uniprotkb:HIST1H3F(gene name)|uniprotkb:HIST1H3G(gene name)|uniprotkb:HIST1H3H(gene name)|uniprotkb:HIST1H3I(gene name)|uniprotkb:HIST1H3J(gene name)' 
>>> re.findall(r'uniprotkb:([^(]*)\(gene name\)', sstr)

['HIST1H3D', 'HIST1H3A', 'HIST1H3B', 'HIST1H3C', 'HIST1H3E', 'HIST1H3F', 'HIST1H3G', 'HIST1H3H', 'HIST1H3I', 'HIST1H3J']

答案 1 :(得分:0)

这是一个oneliner:

astr = 'uniprotkb:HIST1H3D(gene name)|uniprotkb:HIST1H3A(gene name)|uniprotkb:HIST1H3B(gene name)|uniprotkb:HIST1H3C(gene name)|uniprotkb:HIST1H3E(gene name)|uniprotkb:HIST1H3F(gene name)|uniprotkb:HIST1H3G(gene name)|uniprotkb:HIST1H3H(gene name)|uniprotkb:HIST1H3I(gene name)|uniprotkb:HIST1H3J(gene name)'
[pt.split('(')[0] for pt in astr.strip().split('uniprotkb:')][1:]

给出:

['HIST1H3D',
 'HIST1H3A',
 'HIST1H3B',
 'HIST1H3C',
 'HIST1H3E',
 'HIST1H3F',
 'HIST1H3G',
 'HIST1H3H',
 'HIST1H3I',
 'HIST1H3J']

如果运行时很重要,我不推荐使用regexp解决方案。

答案 2 :(得分:-1)

我不打扰正则表达式:

s = 'uniprotkb:HIST1H3D(gene name)|uniprotkb:HIST1H3A(gene name)'  # etc

gene_names = []
for substring in s.split('|'):
    removed_first = substring.partition('uniprotkb:')[2]  # remove the first part of the substring
    removed_second = removed_first.partition('(gene name)')[0]  # remove the second part
    gene_names.append(removed_second)  # put it on the list

应该做的伎俩。你甚至可以单行 - 上面相当于:

gene_names = [substring.partition('uniprotkb:')[2].partition('(gene name)')[0] for substring in s.split('|')]