Search code examples
pythonregexcommentspyparsing

Pyparsing ignore except


I have a file, with pythonStyleComments in lines, for example:

def foo(): # declare
    # Simple function
    a = 0 # TODO: add random
    return a

So, then I want to add .ignore(pythonStyleComments) to pyparsing, but want to handle any meta (such as TODO: ). I know all meta words, so how I can exclude this comments from ignoring?

Maybe declare comment as '#' + Regex(), where Regex would be exclude meta words? Or pyparsing has more elegant method?


Solution

  • I have just declared comment = Literal('#').suppress() + Optional(restOfLine)

    and then add it as Optional(comment) to the end of each statement, where it could appear. Then add

    def commentHandler(t):
        result = []
        if "fixed" in t[0]:
            result.append("fixed")
        if "TODO: " in t[0]:
            try:
                message = t[0].split("TODO: ")[1].strip()
                result.append(message)
            except Exception as e:
                result.append(t[0])
        return result
    
    comment.setParseAction(commentHandler)
    

    So it works perfectly for me.