首页 > 解决方案 > 用于捕获两个子字符串之间的字符串的正则表达式

问题描述

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

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

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

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

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

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

标签: pythonregexregex-lookaroundsregex-groupregex-greedy

解决方案


您可能不希望有任何环顾四周来获得所需的输出。您可以简单地使用类似于此表达式的表达式来执行此操作:

(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中可视化您的表达式:

在此处输入图像描述


推荐阅读