Search code examples
pythonpyparsing

Skip to first possibility in text with pyparsing


I am using pyparsing and am trying to use the method Skipto to reach the first occurence of several possible Literals in the text.

Imagine something similar to this:

OneOrMore(SkipTo(...longer expression...) | SkipTo(...another long expression...))

And I cannot fuse the two SkipTo's as they are located in different classes and it would not fit into the current system to fuse those classes.

If I now have a text similar to this one:

...a lot of stuff...
Example2
...more stuff...
Example1
...stuff...

It only finds the Example1 occurence and just ignores the other one. Now my question is how I can skip to the first possibility in the file and thus find all occurences.


Solution

  • If you are only trying to process bits and pieces from within a larger body of text, try using searchString or scanString instead of parseString.

    from pyparsing import oneOf, lineno
    
    sample = """
    <<Lot of stuff>>
    Example2
    <<More stuff>>
    Example1
    <<Stuff>>"""
    
    expr = oneOf("Example1 Example2")
    
    for toks, start, end in expr.scanString(sample):
        print toks
        print "starts at line", lineno(start, sample)
        print "ends at line", lineno(end, sample)
        print
    

    prints

    ['Example2']
    starts at line 3
    ends at line 3
    
    ['Example1']
    starts at line 5
    ends at line 5