【问题标题】:How to use RegEx to find a consecutively repeating string and return a list of matches in Python [duplicate]如何使用RegEx查找连续重复的字符串并在Python中返回匹配列表[重复]
【发布时间】:2020-06-17 06:51:26
【问题描述】:

我想知道是否可以返回一个匹配列表,其正则表达式模式由一个特定的、连续重复的字符串组成,例如“添加”。这听起来可能微不足道,实际上根据 regexpal.com,它应该像这样简单:“(AGATC)\1+”: result in regexpal.com。并且使用re.findall,如文档中所述,应该返回一个包含所有这些匹配项的列表。 但是,使用此代码时:

pattern = r"(AGATC)\\1+"
list_of_results = re.findall(pattern, seq_string)
print("list of results:", list_of_results)

其中seq_string 是我正在寻找模式的字符串,并且与正则表达式图像中使用的字符串相同,我得到一个包含模式('AGATC')的 1 个元素的数组。

可以做我需要的吗?也许我忽略了什么?

【问题讨论】:

  • 您可以发布示例输入和预期输出
  • @komatiraju033 是的!如果您查看照片,那是示例输入,预期的输出是一个列表,其中突出显示了匹配的字符串,或者如果有多个字符串,则为字符串。我认为通过查看照片更容易理解,而不是在此处复制粘贴实际字符串,因为很难看到其中所需的图案在哪里。
  • 您需要将您的正则表达式定义为pattern = r"(AGATC)\1+"pattern = "(AGATC)\\1+"。请改用re.finditer ([x.group() for x in re.finditer(pattern, s)])(如here 所述)。

标签: python python-3.x regex python-re


【解决方案1】:

您的问题是re.findall 只会在正则表达式中存在一个(或多个)时返回捕获组的内容。您可以通过使用外部组捕获整个匹配来解决此问题,例如:

pattern = r"((AGATC)\2+)"
list_of_results = re.findall(pattern, seq_string)
print("list of results:", list_of_results)

这会给你一个类似的结果:

[('AGATCAGATCAGATC', 'AGATC')]

您可以使用列表推导仅返回每个结果的第一个值,例如

list_of_results = [g[0] for g in re.findall(pattern, seq_string)]

得到类似的东西:

['AGATCAGATCAGATC']

或者您可以使用re.finditer 并根据它生成的匹配对象构建您的列表:

pattern = r"(AGATC)\1+"
list_of_results = [m.group() for m in re.finditer(pattern, seq_string)]
print("list of results:", list_of_results)

这会给你这样的结果:

['AGATCAGATCAGATC']

【讨论】:

  • 谢谢!在第一个解决方案中,为什么 \2 有效而不是 \1?
  • @JorgePasco 那是因为外部组现在是第 1 组,而内部组(您要重复)是第 2 组。
【解决方案2】:

试试这个:

import re

res = re.findall('AGATC', seq_string)
print(res)

【讨论】:

    猜你喜欢
    • 2019-09-04
    • 2020-01-16
    • 2023-03-31
    • 2017-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-11
    相关资源
    最近更新 更多