Skip to first possibility in text with pyparsing

怎甘沉沦 提交于 2019-12-24 11:32:02

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/32439662/skip-to-first-possibility-in-text-with-pyparsing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!