How to split comma-separated key-value pairs with quoted commas

后端 未结 5 1475
终归单人心
终归单人心 2021-01-02 13:03

I know there are a lot of other posts about parsing comma-separated values, but I couldn\'t find one that splits key-value pairs and handles quoted commas.

I have st

5条回答
  •  借酒劲吻你
    2021-01-02 13:51

    It's possible to do with a regular expression. In this case, it might actually be the best option, too. I think this will work with most input, even escaped quotes such as this one: phrase='I\'m cool'

    With the VERBOSE flag, it's possible to make complicated regular expressions quite readable.

    import re
    text = '''age=12,name=bob,hobbies="games,reading",phrase="I'm cool!"'''
    regex = re.compile(
        r'''
            (?P\w+)=      # Key consists of only alphanumerics
            (?P["']?)   # Optional quote character.
            (?P.*?)     # Value is a non greedy match
            (?P=quote)         # Closing quote equals the first.
            ($|,)              # Entry ends with comma or end of string
        ''',
        re.VERBOSE
        )
    
    d = {match.group('key'): match.group('value') for match in regex.finditer(text)}
    
    print(d)  # {'name': 'bob', 'phrase': "I'm cool!", 'age': '12', 'hobbies': 'games,reading'}
    

提交回复
热议问题