Search code examples
pythonpyparsing

Pyparsing -Match literal at start of line ignoring whitespace


Trying to match this

create

or

create

but not

#  create

This doesn't work.

(LineStart() + CaselessLiteral('create')).searchString('''
   create
''')

Nor does this

(LineStart() + White(min=0).suppress() + CaselessLiteral('create')).searchString('''
   create
''')

Solution

  • Pyparsing's whitespace-skipping is confusing the issue here, and LineStart() is a finicky class to work with anyway.

    The core issue is that every pyparsing element runs a pre-parse routine, to skip over whitespace and any ignorable expressions (like comments). In your case, LineStart's pre-parse routine is skipping over the leading whitespace! So it is evaluating "is this the start of a line?" not at column 1, but at column 4, where you have the first letter in "create".

    You can suppress this whitespace-skipping on your LineStart element by calling leaveWhitespace - that is, don't skip over whitespace during the pre-parse function. This would look like:

    print((LineStart().leaveWhitespace() + CaselessLiteral('create')).searchString('''\
       create
    '''))
    

    which will print:

    [['create']]