我的代码是这样的:
string = "title=abcd color=green title=efgh color=blue title=xyxyx color=yellow title=whatIwaht color=red title=xxxy red=anything title=xxxyyy color=red"
pattern = r'title=(.*?) color=red'
print re.compile(pattern).search(string).group(0)
我得到了
"title=abcd color=green title=efgh color=blue title=xyxyx color=yellow title=whatIwaht color=red title=xxxy red=anything title=xxxyyy color=red"
但我想找到紧跟“color=red”的“title”的所有内容
最佳答案
您想要紧接在 color=red
之前的内容吗?然后使用
.*title=(.*?) color=red
演示:https://regex101.com/r/sR4kN2/1
这会贪婪地匹配 color=red
之前的所有内容,以便只显示所需的标题。
或者,如果您知道有一个字符没有出现在标题中,您可以通过使用字符类排除来简化。例如,如果您知道 =
不会出现:
title=([^=]*?) color=red
或者,如果您知道不会出现空格:
title=([^\s]*?) color=red
第三个选项,使用一些代码来查找所有红色标题(假设输入总是交替显示标题、颜色):
for title, color in re.findall(r'title=(.*?) color=(.*?)\( |$\)'):
if color == 'red':
print title
关于python - 如何获取字符串中键的值,后跟另一个特定的键=值集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30883312/