Search code examples
pythonpyparsing

How to define an optional word in pyparse grammar?


I'm parsing sql code objects for the object name and for views I noticed that there are optional keywords that could throw my grammar off. I think I need to be able to define an optional keyword but I have not found a way to do so.

For example

viewDefinition = "CREATE OR REPLACE VIEW" + Word( alphas+"_", alphanums+"_") 
forceviewLine = "CREATE OR REPLACE FORCE VIEW VW_MY_TEST_VIEW"

print(forceviewLine,"->", viewDefinition.parseString(forceviewLine))
viewname = viewDefinition.parseString(forceviewLine)[1]

Because the grammar doesn't fit anymore I'd encounter the following error

pyparsing.ParseException: Expected "CREATE OR REPLACE VIEW" (at char 0), (line:1, col:1)

Is there a way to define an optional keyword on the grammar that could come before the keyword VIEW and that I can get the VW_MY_TEST_VIEW code object name?


Solution

  • I figured it out thought it might be useful for others so I'm answering myself.

    COR = CaselessLiteral('CREATE OR REPLACE') 
    optFORCEkw = Optional(CaselessLiteral('FORCE'))
    V = CaselessLiteral('VIEW')
    
    
    forceviewLine = "CREATE OR REPLACE FORCE VIEW VW_MY_TEST_VIEW"
    normalviewLine = "CREATE OR REPLACE VIEW VW_MY_TEST_VIEW"
    
    newGrammer2 = COR + optFORCEkw + V + Word( alphas+"_", alphanums+"_") 
    print(forceviewLine,"->", newGrammer2.parseString(forceviewLine))
    print(normalviewLine,"->", newGrammer2.parseString(normalviewLine))