【问题标题】:Extract substring between two specified substrings using re.search(pattern, text) in Python在 Python 中使用 re.search(pattern, text) 提取两个指定子字符串之间的子字符串
【发布时间】:2020-09-22 12:13:13
【问题描述】:

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

我试过了,

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'

请帮帮我。

【问题讨论】:

  • 你能解释一下你的正则表达式中的嵌套括号吗?
  • 我试图首先匹配“_”开始之前的所有大写字母或数字字母,然后匹配“_BS”之前的所有内容。我是正则表达式的新手,所以我不确定我所做的是否正确。
  • 括号用来指定一组有效的字符;您正在尝试将它们用于更多用途。

标签: python regex list python-2.7 substring


【解决方案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')])]

【讨论】:

    【解决方案2】:

    您可以使用生成器而不是正则表达式轻松实现此目的:

    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

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

    正则表达式有用的时间和空间。但在此之前,不要将它不必要地添加到您的问题中。

    【讨论】:

      猜你喜欢
      • 2020-09-22
      • 2013-01-31
      • 2013-12-11
      • 1970-01-01
      • 1970-01-01
      • 2020-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多