python - 如何使用多字符通配符执行 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”。
如何进行修剪多字符计数器的强大修剪?
解决方案
在您的正则表达式(?<=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
推荐阅读
- protractor - 在量角器中设置请求标头
- javascript - PayPal Express (checkout.js):禁用输入键
- rust - 如何使用 openssl 交叉编译 rust 项目?
- memory - RapidJSON 在从复杂文档中删除成员后不会重用内存
- html - 移动版上不需要的空白
- vtk - 我们应该如何在 VTK 中对这个简单的数据文件进行体绘制?
- mysql - 问题输出最有经验的价值
- pgadmin - 如何保存 pgAdmin 布局
- dart - Formatting a Duration like HH:mm:ss
- swift - 是否可以为“DispatchQueue.concurrentPerform”指定“DispatchQueue”?