Regex match for dictionary elements

时间:2018-04-18 18:05:19

标签: python regex

I am doing a regex pattern match for the following input, with the regex \-\-(.*)\=(.*[\w\s\n\Z\r]*)

--key_a=value1
--key_b=value2
--key_c=value3
--key_d=value4
--key_e=-----BEGIN CERTIFICATE-----\nHYxCzAJBgNV--=B+AYT\AlVTM/QswCQYDVQQIDAJDQTE=RMA8GA1UEBwwIU2FuIEpvc2UxFTATBgNVBAoMDE51dGFuaXg\r\n

But the regex matches incorrectly when the value of key contains one or more = signs. I want the key_e as the first group and everything after first = and before next -- as the second group. How to solve this?

1 个答案:

答案 0 :(得分:1)

You could use --(.*?)=(.*). Uses ungreedy matching to find everything between -- and the first =, and then greedily matches everything after.

x = """
--key_a=value1
--key_b=value2
--key_c=value3
--key_d=value4
--key_e=valuewith======init========
"""
import re
print(re.findall(r'--(.*?)=(.*)', x))

Output:

[('key_a', 'value1'), ('key_b', 'value2'), ('key_c', 'value3'), ('key_d', 'value4'), ('key_e', 'valuewith======init========')]