python - 提取 2 个字符串之间的字符串,如果未找到第 2 个字符串,则提取到末尾
问题描述
如果找不到第二个字符串,在 2 个字符串之间提取字符串并提取到末尾的模式是什么?例如:检索分配给 foo 的值(值包含空格)
import re
s1 = 'quz=1, 2, 3 and foo=4, 5, 6 and bar=7, 8, 9'
m = re.match(pattern=r'^.*foo=(.*)\sand', string=s1)
assert m.group(1) == '4, 5, 6'
s2 = 'quz=1, 2, 3 and foo=4, 5, 6'
m = re.match(pattern=r'^.*foo=(.*)', string=s2)
assert m.group(1) == '4, 5, 6'
谢谢
解决方案
您可以将前瞻 (?=...)与or逻辑(and
字符串的下一个或结尾$
)一起使用:
re.search
由于您不是从字符串的开头匹配,因此使用;可能更方便 .*?
如果您只想匹配下一个,非贪婪的正则表达式更适合and
;
import re
re.search(r'foo=(.*?)(?= and|$)', s1).group(1)
# '4, 5, 6'
re.search(r'foo=(.*?)(?= and|$)', s2).group(1)
# '4, 5, 6'
推荐阅读
- kubernetes - 基于 pod 或部署的 GKE 账单明细
- java - 找出数字之间的阿姆斯壮数
- cloud-foundry - 没有一个 buildpack 检测到兼容的应用程序
- joomla - Joomla 文件未找到错误
- unity3d - 如何在 Unity 上使用 Google Text-To-Speech?
- ios - Cocopods Post_Install 脚本错误
- mongodb - 如何在 mongo db 聚合的下一行访问 $project 字段
- python - 使用 TensorFlow 处理图像
- ssl - 来自开发服务器上的在线域的 SSL 证书?
- python - 查找多米诺骨牌顺序的有效方法