Regular expression to match comma separated list of key=value where value can contain commas

前端 未结 5 693
一生所求
一生所求 2020-12-20 15:54

I have a naive \"parser\" that simply does something like:
[x.split(\'=\') for x in mystring.split(\',\')]

However mystring can be something like<

5条回答
  •  不知归路
    2020-12-20 16:37

    Could I suggest that you use the split operations as before. But split at the equals first, then splitting at the rightmost comma, to make a single list of left and right strings.

    input =
    "bob=whatever,king=kong,banana=herb,good,yellow,thorn=hurts"
    

    will at first split become

    first_split = input.split("=")
    #first_split = ['bob' 'whatever,king' 'kong,banana' 'herb,good,yellow,thorn' 'hurts']
    

    then splitting at rightmost comma gives you:

    second_split = [single_word for sublist in first_split for item in sublist.rsplit(",",1)]
    #second_split = ['bob' 'whatever' 'king' 'kong' 'banana' 'herb,good,yellow' 'thorn' 'hurts']
    

    then you just gather the pairs like this:

    pairs = dict(zip(second_split[::2],second_split[1::2]))
    

提交回复
热议问题