Python Pyparsing: grab a comma separated list in parentheses, ignoring inner brackets

I have a question on how to parse a string correctly, as shown below,

"(test.function, arr(3,12), "combine,into one")"

to the following list,

['test.function', 'arr(3,12)', '"combine,into one"']

Note. Elements of the “list” from the source string are not necessarily separated by a comma and a space, it can also be two elements separated directly by a comma one after another, for example. test.function,arr(3,12).

Basically, I want:

  • Parse the input string, which is enclosed in parentheses, but not inside brackets. (Therefore, nestedExpr()you cannot use as-is)
  • Elements inside are separated by commas, but the elements themselves may contain commas.

In addition, I can use only scanString(), not parseString().

SO , .

!

+4
2

:

sample = """(test.function, arr(3,12),"combine,into one")"""

from pyparsing import (Suppress, removeQuotes, quotedString, originalTextFor, 
    OneOrMore, Word, printables, nestedExpr, delimitedList)

# punctuation and basic elements
LPAR,RPAR = map(Suppress, "()")
quotedString.addParseAction(removeQuotes)

# what are the possible values inside the ()'s?
# - quoted string - anything is allowed inside quotes, match these first
# - any printable, not containing ',', '(', or ')', with optional nested ()'s
#   (use originalTextFor helper to extract the original text from the input
#   string)
value = (quotedString 
         | originalTextFor(OneOrMore(Word(printables, excludeChars="(),") 
                                     | nestedExpr())))

# define an overall expression, with surrounding ()'s
expr = LPAR + delimitedList(value) + RPAR

# test against the sample
print(expr.parseString(sample).asList())

:

['test.function', 'arr(3,12)', 'combine,into one']
+1

+ .

a = """(test.function, arr(3,12), "combine,into one")"""
a[1:-1].split(", ")
# ['test.function', 'arr(3,12)', '"combine,into one"']

. , , , .

['test.function','arr(3,12)','"combine,into one"']
0

Source: https://habr.com/ru/post/1661232/


All Articles