Search code examples
pythonpyparsing

Parse key-value pairs with pyparsing where values may continue over multiple lines


How can I parse key-property definitions such as the following with pyparsing?

some_key a b c d
other_key /some/path /some/other/path.pl \
  '$SOME_ENV_VAR$' \
  '$OTHER_ENV_VAR$'

Keys in this example are some_key and other_key. Values are the rests of the lines including [ \t] after whitespace that is following the key names, with an option for line continuation with \.

I am relatively new to pyparsing and this exceeds my current capabilities.


Solution

  • The source code for pyparsing (e.g. for cppStyleComment) was instructive and the following now works for me:

    name = pp.Word(pp.alphas + '_', pp.alphanums + '_')
    value = pp.Regex(r'(?:[^\n]*\\\n)*[^\n]*')
    definition = name + value