【问题标题】:RegEx for capturing a string between two substrings用于捕获两个子字符串之间的字符串的正则表达式
【发布时间】:2019-05-15 21:49:10
【问题描述】:

我正在尝试提取文本文件中所有出现的模式(它是来自 DNA 样本的氨基酸序列)。

我要匹配的模式是 MetSOMETEXT***

源字符串中多次出现该模式,我正在尝试获取所有。

我目前正在使用 re.findall 在 python 中执行此操作,但它不起作用。

orfs = re.findall('(?<=Met).*(?=\*\*\*)' , translatedSequence)

我希望得到一个包含结果的字符串列表。

【问题讨论】:

  • 如果我理解你的话,你的代码应该可以正常工作。
  • 可能是orfs = re.findall('(?&lt;=Met)[^*]*(?=\*\*\*)' , translatedSequence) 你的表达式使用了一个贪婪的匹配,.* 在尝试匹配(?=\*\*\*) 之前,它会在字符串的最右边,我建议的更改将匹配非* up到***
  • 要允许* 捕获不是连续3 个*,orfs = re.findall('(?.*? 使其成为非贪婪匹配

标签: python regex regex-lookarounds regex-group regex-greedy


【解决方案1】:

您可能不希望有任何环顾四周来获得所需的输出。您可以简单地使用类似于this expression 的表达式来做到这一点:

(Met)(.*)(\*\*\*)

共有三个捕获组,其中第二个是您想要的输出。

Python 测试

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"(Met)(.*)(\*\*\*)"

test_str = "MetSOMETEXT***"

subst = "\\1\\2"

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)

if result:
    print (result)

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.

输出

MetSOMETEXT

JavaScript 演示

const regex = /(Met)(.*)(\*\*\*)/gm;
const str = `MetSOMETEXT***`;
const subst = `$1$2`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log('Substitution result: ', result);

正则表达式

如果这不是您想要的表达方式,您可以在regex101.com 中修改/更改您的表达方式。

正则表达式电路

您还可以在jex.im 中可视化您的表达式:

【讨论】:

  • 哇,反应真棒,完全暴露了我对这个话题的无知。原始问题只有一个模式,我需要保留“Met”,当前的正则表达式似乎放松了搜索。我会尝试一些变体,看看有什么效果。
猜你喜欢
  • 1970-01-01
  • 2018-03-22
  • 1970-01-01
  • 2020-03-23
  • 2014-12-08
  • 2013-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多