need help First timer with pyparsing

asri
2012-12-13
2013-05-14
  • asri
    asri
    2012-12-13

    how do i parse a simple expression as below

    <identifier> = ('<singlequotedstring>', literal,'<singlequotedstring>', literal,…) it can only end in '<singlequotedstring>'

     
  • Paul McGuire
    Paul McGuire
    2012-12-16

    Looks like:

    identifier + '=' + singleQuotedString + ZeroOrMore(literal + singleQuotedString)
    
     
  • asri
    asri
    2012-12-17

    Thanks Paul. This works.
    Additionally is there a way that the parse exception can show little more information.

    The message is clear but is there a way to add more information.

    Existing: ParseException: Expected ")" (at char 48), (line:1, col:49)
    Modified: ParseException: Expected ")" but found "OR" (at char 48), (line:1, col:49)

     
  • Paul McGuire
    Paul McGuire
    2012-12-18

    You can output your own diagnostics using properties of the ParseException that is raised:

    >>> from pyparsing import *
    >>> identifier = Word(alphas)
    >>> singleQuotedString = sglQuotedString
    >>> literal = ","
    >>> expr = identifier + '=' + singleQuotedString + ZeroOrMore(literal + singleQuotedString)
    >>> try:
    ...    expr.parseString('xyz = 123')
    ... except ParseException as pe:
    ...    exc = pe
    ...
    >>> print(exc)
    Expected string enclosed in single quotes (at char 6), (line:1, col:7)
    >>> dir(exc)
    ['__repr__', '__str__', 'col', 'line', 'lineno', 'loc', 'markInputline', 'msg', 'parserElement', 'pstr']
    >>> print(exc.col)
    7
    >>> print (exc.line)
    xyz = 123
    >>> print (exc.msg + '\n' + exc.line + '\n' + ' '*(exc.col-1) + '^')
    Expected string enclosed in single quotes
    xyz = 123
          ^
    

    (Urgh! there is a bug in markInputline, which would normally simplify this process - well until I ship a fix, you can use this method as a workaround.)