python - 如何获取字符串中键的值,后跟另一个特定的键=值集

标签 python regex

我的代码是这样的:

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/

相关文章:

python - 如何在特定情况下组合数据框?

ruby - 如何在 Ruby 正则表达式中插入变量?

java - 正则表达式:匹配其他正则表达式剩下的所有内容

regex - 按相似词分组

Python WSGI + Flask render_template - 500 内部服务器错误?

python - OpenCV 错误 : bad argument, 重载解析失败,索引为 0 的序列项类型错误

python - 文本挖掘和 NLP : from R to Python

python - 如何重启 PyQt5 应用程序

Javascript JSON对象替换对象内的字符串

javascript - jQuery 数据选择器中正则表达式的性能 : dependance on certain string length