简体   繁体   中英

pyparsing conditional parser

I need to parse the following three lines:

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

But last two lines are not always there, output could look like this prior to 1st reboot:

Uptime is 1w2d
Last reset

My parser looks like this:

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

It works in first case with 3 lines, but doesnt work with second case.

I will use for the file that you've reported this syntax (supposing that the order is relevant):

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))

Declaring a parsing element optional you are able to let the parser skip it when it is not present, without raising any errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM