首页 > 解决方案 > 如何使用多字符通配符执行 Python re.search 子字符串?

问题描述

我正在尝试从 Python 中的字符串中提取子字符串。要修剪的前端是静态的,易于实现,但后端有一个可以从“_0”到“_9999”运行的计数器。

使用我当前的代码,计数器仍然包含在子字符串中。

import re

text = "fastq_runid_0dc971f49c42ffb1412caee485f8421a1f9a26ed_0.fastq"

print(text)
substring= re.search('runid_(.*)_*.fas', text).group(0)

print(substring)

退货

0dc971f49c42ffb1412caee485f8421a1f9a26ed_0.fas

或者,

substring= re.search(r"(?<=runid_).*?(?=_*.fastq)", text).group(0)

返回

0dc971f49c42ffb1412caee485f8421a1f9a26ed_0

效果更好,但仍添加了计数器“_0”。

如何进行修剪多字符计数器的强大修剪?

标签: pythonregexstringsubstring

解决方案


在您的正则表达式(?<=runid_).*?(?=_*.fastq)中有一个小问题。你已经写_*了这意味着零个或多个下划线,这将使下划线成为可选的并且会跳过它匹配并且你.*?也会在其中吃东西_0,这就是为什么你的结果_0也会得到。我认为你的意思是_.*,你也应该逃避.之前,fastq所以你更新的正则表达式应该变成这个,

(?<=runid_).+(?=_\d{1,4}\.fas)

演示

你更新的python代码,

import re

text = "fastq_runid_0dc971f49c42ffb1412caee485f8421a1f9a26ed_0.fastq"

print(text)
substring= re.search('(?<=runid_).+(?=_\d{1,4}\.fas)', text).group(0)

print(substring)

印刷,

0dc971f49c42ffb1412caee485f8421a1f9a26ed

此外,或者,您可以使用没有环视的简单正则表达式,并使用此正则表达式从第一组捕获文本,

runid_([^_]+)(?=_\d{1,4}\.fas)

演示

您的 python 代码与文本选择group(1)而不是group(0)

import re

text = "fastq_runid_0dc971f49c42ffb1412caee485f8421a1f9a26ed_0.fastq"

print(text)
substring= re.search('runid_([^_]+)(?=_\d{1,4}\.fas)', text).group(1)

print(substring)

在这种情况下,它也会打印,

0dc971f49c42ffb1412caee485f8421a1f9a26ed

推荐阅读