我有一个关于如何正确解析字符串的问题,如下所示,
$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"']
。
基本上,我想:
答案 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"']