使用Python中的re.search(pattern,text)在两个指定的子字符串之间提取子字符串

问题描述 投票:1回答:2

我有一个类似"ENST00000260682_3_4_5_6_7_8_9_BS_673.6"的字符串。我必须在re.search()中使用正则表达式来提取子字符串,并将其写入Python这样的列表中,例如[3, 4, 5, 6, 7, 8, 9]

我尝试过,

text="ENST00000260682_3_4_5_6_7_8_9_BS_673.6"
pattern=re.compile(r"^[[A-Z0-9]*_[.*]_BS]")
a=re.search(pattern, text)
print(a.group())

它返回,'none',还有AttributeError: 'NoneType' object has no attribute 'group'

请帮助我。

python regex list python-2.7 substring
2个回答
1
投票

_BS之前的下划线之后搜索所有数字:

import re
text="ENST00000260682_3_4_5_6_7_8_9_BS_673.6"
pattern=re.compile(r"_(\d+)")
a=re.findall(pattern, text[:text.find('_BS')])
print(a)

输出:['3', '4', '5', '6', '7', '8', '9']

或根据需要将它们强制转换为int:

a=[int(x) for x in re.findall(pattern, text[:text.find('_BS')])]

1
投票

您可以使用生成器而不是正则表达式轻松实现这一点:

def num_gen(s, delimiter='_', start_index=1, stop_token='BS'):
    # delimiter: the char you want to split your text for
    # start_index: where your want to start retrieving values
    # stop_token: stop retrieving when the token is encountered

    for x in s.split(delimiter)[start_index:]:
        if x != stop_token:
            yield x
        else:
            return

用法:

t = "ENST00000260682_3_4_5_6_7_8_9_BS_673.6"
list(num_gen(t))

# ['3', '4', '5', '6', '7', '8', '9']

[如果可能,我建议除非必要,否则避免使用正则表达式,如果您不熟悉,请尤其是。这是一个relevant quote

有些人在遇到问题时会想 “我知道,我将使用正则表达式。” 现在他们有两个问题。

正则表达式有用的时间和空间。但在此之前,请不要不必要地将其添加为问题的一部分。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.