使用列表:
list
不是派生自的实例pypeg2.Concat
代表不同的选项。它们按顺序进行测试。选择第一个解析的选项,其他的不再测试。如果没有匹配,SyntaxError
则引发 a。
例如:
from pypeg2 import K, List, maybe_some, parse
class Apple:
grammar = K('apple')
class Banana:
grammar = K('banana')
class Lime:
grammar = K('lime')
class Orange:
grammar = K('orange')
class FruitBasket(List):
'''An unordered collection of zero or more fruits'''
grammar = maybe_some([Apple, Banana, Lime, Orange])
if __name__ == '__main__':
fruit = '''
orange
apple
orange
apple
apple
lime
banana
'''
print(parse(fruit, FruitBasket))
输出:
FruitBasket([<__main__.Orange object at 0x7ffa4991d8d0>, <__main__.Apple object at 0x7ffa49922c18>, <__main__.Orange object at 0x7ffa49927a58>, <__main__.Apple object at 0x7ffa499279b0>, <__main__.Apple object at 0x7ffa49927908>, <__main__.Lime object at 0x7ffa421ad828>, <__main__.Banana object at 0x7ffa421ad8d0>])