修改了原始示例。我不知道他們爲什麼從原始腳本中刪除enum.ignore(cppStyleComment)
。把它放回去。
from pyparsing import *
# sample string with enums and other stuff
sample = '''
stuff before
enum hello {
Zero,
One,
Two,
Three,
Five=5,
Six,
Ten=10,
minusone=-1,
par1 = ((0,5)),
par2 = sizeof("a\\")bc};,"),
par3 = (')')
};
in the middle
enum
{
alpha,
beta,
gamma = 10 ,
zeta = 50
};
at the end
'''
# syntax we don't want to see in the final parse tree
LBRACE,RBRACE,EQ,COMMA = map(Suppress,"{}=,")
lpar = Literal("(")
rpar = Literal(")")
anything_topl = Regex(r"[^'\"(,}]+")
anything = Regex(r"[^'\"()]+")
expr = Forward()
pths_or_str = quotedString | lpar + expr + rpar
expr << ZeroOrMore(pths_or_str | anything)
expr_topl = ZeroOrMore(pths_or_str | anything_topl)
_enum = Suppress('enum')
identifier = Word(alphas,alphanums+'_')
expr_topl_text = originalTextFor(expr_topl)
enumValue = Group(identifier('name') + Optional(EQ + expr_topl_text('value')))
enumList = Group(ZeroOrMore(enumValue + COMMA) + Optional(enumValue))
enum = _enum + Optional(identifier('enum')) + LBRACE + enumList('names') + RBRACE
enum.ignore(cppStyleComment)
# find instances of enums ignoring other syntax
for item,start,stop in enum.scanString(sample):
for entry in item.names:
print('%s %s = %s' % (item.enum,entry.name, entry.value))
結果:
$ python examples/cpp_enum_parser.py
hello Zero =
hello One =
hello Two =
hello Three =
hello Five = 5
hello Six =
hello Ten = 10
hello minusone = -1
hello par1 = ((0,5))
hello par2 = sizeof("a\")bc};,")
hello par3 = (')')
alpha =
beta =
gamma = 10
zeta = 50
沒有注意到nestedExpr。謝謝 – basin