Question

I am trying to get a block of lines between 2 known lines using pyparsing. For example:

ABC
....
DEF

My python code:

end = Literal("\n").suppress()
firstLine = Literal("ABC") + SkipTo(end)
secondLine = Literal("DEF") + SkipTo(end)
line = SkipTo(end)
test = firstLine + OneOrMore(line) + secondLine

test.searchString(myText)

--> but it doesn't work. Python just hangs. Can anybody show me how to do it?

Thanks,

Was it helpful?

Solution 2

I finally found answer to my question.

end = Literal("\n").suppress()
firstLine = Literal("ABC") + SkipTo(end)
secondLine = Literal("DEF") + SkipTo(end)
line = ~secondLine + SkipTo(end)
test = firstLine + OneOrMore(line) + secondLine

test.searchString(myText)

That works for me.

OTHER TIPS

Add this debugging code to your program:

firstLine.setName("firstLine").setDebug()
line.setName("line").setDebug()
secondLine.setName("secondLine").setDebug()

and change searchString to parseString. setDebug() will print out every time an expression is about to be attempted to match, and if matched, what got matched, and if not matched, the exception. With your program, after making these changes I get:

Match firstLine at loc 0(1,1)
Matched firstLine -> ['ABC', '.... ']
Match line at loc 11(3,1)
Matched line -> ['DEF ']
Match line at loc 15(3,1)
Exception raised:Expected line (at char 17), (line:4, col:2)
Match secondLine at loc 15(3,1)
Exception raised:Expected "DEF" (at char 16), (line:4, col:1)
Traceback (most recent call last):
  File "rrrr.py", line 19, in <module>
    test.parseString(myText) 
  File "C:\Python25\lib\site-packages\pyparsing-1.5.5-py...
    raise exc
pyparsing.ParseException: Expected "DEF" (at char 16), (line:4, col:1)

Probably not what you expected.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top