pyparsing条件解析器

时间:2014-08-11 15:33:35

标签: python pyparsing

我需要解析以下三行:

Uptime is 1w2d
Last reset at 23:05:56
  Reason: reload

但是最后两行并不总是存在,在第一次重启之前输出看起来像这样:

Uptime is 1w2d
Last reset

我的解析器看起来像这样:

parser = SkipTo(Literal('is'), include=True)('uptime') +
         delimitedList(Suppress(SkipTo(Literal('at'), include=True))'(reset)' +
             SkipTo(Literal(':'), include=true) +
             SkipTo(lineEnd)('reason'), combine=True)
         )

它适用于第一种情况,有3行,但不适用于第二种情况。

1 个答案:

答案 0 :(得分:2)

我将用于您已报告此语法的文件(假设订单相关):

from pyparsing import Literal, Word, alphanums, nums, alphas, Optional, delimitedList

def createParser():
    firstLine = Literal('Uptime is') + Word(alphanums)
    secLine = Literal('Last reset at') + delimitedList(Word(nums) + Literal(':') + Word(nums) + Literal(':') + Word(nums))
    thirdLine = Literal('Reason:') + Word(alphas)

    return firstLine + secLine + Optional(thirdLine)

if __name__ == '__main__':
     parser = createParser()
     firstText = """Uptime is 1w2d\n
     Last reset at 23:05:56\n
     Reason: reload"""

     print(parser.parseString(firstText))

声明解析元素可选,您可以让解析器在不存在时跳过它,而不会引发任何错误。