首页 > 解决方案 > 提取 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'

谢谢

标签: pythonregexpython-2.7

解决方案


您可以将前瞻 (?=...)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'

推荐阅读