Python Pyparsing:在括号内捕获以逗号分隔的列表,忽略内部括号

时间:2016-11-18 19:25:17

标签: python regex string parsing pyparsing

我有一个关于如何正确解析字符串的问题,如下所示,

$form_data = unserialize($_SESSION['temp_form_data']);
    // Use form data here

进入以下列表,

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

注意:原始字符串中的“list”项不一定用逗号和空格分隔,也可以是一个接一个地用逗号直接分割的两个项,例如: ['test.function', 'arr(3,12)', '"combine,into one"']

基本上,我想:

  1. 解析括在括号中的输入字符串,但不解析内括号。 (因此,test.function,arr(3,12)不能按原样使用)
  2. 内部的项目以逗号分隔,但项目本身可能包含逗号。
  3. 此外,我只能使用nestedExpr()而不是scanString()

    我已经在SO中进行了一些搜索,找到了thisthis,但我无法翻译它们以适应我的问题。

    谢谢!

2 个答案:

答案 0 :(得分:1)

这应解决您的嵌套和引用问题:

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 :(得分:0)

对于终端括号之间的所有字符,请用逗号+空格分隔。

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"']
相关问题