我建议不要使用正则表达式来完成此任务,因为您要解析的语言不是正则的。
您有一个由多个键值对组成的字符串。解析它的最佳方法不是匹配它的模式,而是正确地标记它。
Python标准库中有一个模块,叫做shlex
,它模仿 POSIX shell 完成的解析,并提供可以轻松根据您的需求进行自定义的词法分析器实现。
from shlex import shlex
def parse_kv_pairs(text, item_sep=",", value_sep="="):
"""Parse key-value pairs from a shell-like text."""
# initialize a lexer, in POSIX mode (to properly handle escaping)
lexer = shlex(text, posix=True)
# set ',' as whitespace for the lexer
# (the lexer will use this character to separate words)
lexer.whitespace = item_sep
# include '=' as a word character
# (this is done so that the lexer returns a list of key-value pairs)
# (if your option key or value contains any unquoted special character, you will need to add it here)
lexer.wordchars += value_sep
# then we separate option keys and values to build the resulting dictionary
# (maxsplit is required to make sure that '=' in value will not be a problem)
return dict(word.split(value_sep, maxsplit=1) for word in lexer)
(split
has a maxsplit
论证,使用起来比分割/切片/连接 https://stackoverflow.com/revisions/38738997/2.)
运行示例:
parse_kv_pairs(
'key1=value1,key2=\'value2,still_value2,not_key1="not_value1"\''
)
Output:
{'key1': 'value1', 'key2': 'value2,still_value2,not_key1="not_value1"'}
我通常坚持使用 shlex 而不是使用正则表达式(在这种情况下更快)的原因是它给您带来的惊喜更少,特别是如果您稍后需要允许更多可能的输入。我从未找到如何使用正则表达式正确解析此类键值对,总会有输入(例如A="B=\"1,2,3\""
)这会欺骗引擎。
如果您不关心此类输入(或者,换句话说,如果您可以确保您的输入遵循正则语言的定义),那么正则表达式就完全没问题。