python - 用于捕获两个子字符串之间的字符串的正则表达式
问题描述
我正在尝试提取文本文件中所有出现的模式(它是来自 DNA 样本的氨基酸序列)。
我要匹配的模式是 MetSOMETEXT***
源字符串中多次出现该模式,我正在尝试获取所有内容。
我目前正在使用 re.findall 在 python 中执行此操作,但它不起作用。
orfs = re.findall('(?<=Met).*(?=\*\*\*)' , translatedSequence)
我希望得到一个包含结果的字符串列表。
解决方案
您可能不希望有任何环顾四周来获得所需的输出。您可以简单地使用类似于此表达式的表达式来执行此操作:
(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中可视化您的表达式:
推荐阅读
- powershell - 从我的合作伙伴中心帐户/委托帐户连接租户的 Azure AD 时出现错误
- javascript - 无法过滤表中使用 Vue 计算的深层数组对象
- azure - 如何创建多租户应用的服务主体
- networking - kubernetes pod 中的代理不会拦截任何 HTTP 流量
- python - Python数组文本排序
- c - C语言中如何通过矩阵约简来改变球体的体积
- ssis - SSIS - Excel 到 txt 文件:如何在 SSMS 中获得与“结果到文本”相同的格式?
- javascript - HTML 和 JS 中的搜索栏
- ruby-on-rails - 如何在 SQL heredoc 中使用 sql IN 查询
- javascript - Angular ng-if 在没有任何条件的情况下隐藏元素