Re: [Pyparsing] How can I determine if a fragment is valid?
Brought to you by:
ptmcg
From: Paul M. <pt...@au...> - 2008-01-15 15:08:31
|
Here is the complete listing of the SQL expression parser I described in the last message. -- Paul from pyparsing import * sql1 = "select where foo = 1 and bar = 2 into result" sql2 = "select where foo = 1 and bar = 2" into_clause = Keyword('into') + restOfLine selectStmt = Keyword('select') + SkipTo(into_clause|StringEnd()).setResultsName('where_condition') identifier = Word(alphas) relationalOperator = oneOf("< = > >= <= != <>") integer = Word(nums) value = integer | sglQuotedString logicalComparison = identifier + relationalOperator + value AND_cl = CaselessLiteral("AND") OR_cl = CaselessLiteral("OR") NOT_cl = CaselessLiteral("NOT") complexComparison = operatorPrecedence( logicalComparison, [ (NOT_cl, 1, opAssoc.RIGHT), (OR_cl, 2, opAssoc.LEFT), (AND_cl, 2, opAssoc.LEFT), ]) where_clause = CaselessLiteral("where") + complexComparison selectStmt = Keyword('select') + where_clause('where_condition') + \ Optional(into_clause)('into_clause') print selectStmt.parseString(sql1).dump() print selectStmt.parseString(sql2).dump() Prints: ['select', 'where', [['foo', '=', '1'], 'AND', ['bar', '=', '2']], 'into', ' result'] - into_clause: ['into', ' result'] - where_condition: ['where', [['foo', '=', '1'], 'AND', ['bar', '=', '2']]] ['select', 'where', [['foo', '=', '1'], 'AND', ['bar', '=', '2']]] - where_condition: ['where', [['foo', '=', '1'], 'AND', ['bar', '=', '2']]] |