# preparser state for regexs

I would have expected the following to work:

reset()
import re

preparser(False)                         # preparser off else we have \\ instead of \
rx=re.compile(r".*(\sHun\s).*")          # in the regex

m = rx.match(r"The Attila the Hun Show") # Find "Hun" in "The Attila the Hun Show"
if m: print "found =>", m.group(1)       # 1 needs to be 1 not '1' here!

preparser(True)


In fact I get 'IndexError: no such group'. Using int(1) fixes the problem, but why? The preparser is off!

Even more curious the block works, as is, on every other evaluate! I tried moving the preparser(False) statement to before the import, but that makes no difference.

edit retag close merge delete

Sort by » oldest newest most voted

This works for me from the command line. In the notebook, it fails the first time and succeeds the second time. Indeed, having a notebook cell containing

preparser(False)
type(2)


fails the first time I evaluate it and succeeds the second time. This is what is supposed to happen, though. Consider this, from the command-line:

sage: preparser(False); type(2)


The first thing that happens is that the whole line gets preparsed, so "2" gets turned into "Integer(2)". Then the line gets evaluated, so it turns the preparser off and it returns the type of "Integer(2)", namely sage.rings.integer.Integer. I think that the same thing happens in each cell of the notebook: the whole thing gets preparsed before any of it is evaluated. So you need to put preparser(False) in a separate cell and evaluate it first.

more

No no no .. Something infinitly more diabolical! Experement with two cells as follows Cell one: preparser(False); print type(2) preparser(True); print type(2) Cell two: preparser(True); print type(2) preparser(False); print type(2) preparser(True) Also comment the last and see what happens. I'm totaly confused. I anycase, surely one should leave the preparser in the on state?

( 2012-08-30 10:33:16 -0600 )edit

I don't see anything wrong with these two cells. Any "preparser" commands cannot affect the current cell, since they haven't been evaluated yet. Once the cell has been evaluated (in its entirety), they affect any further cells, so for both of your cells, since they both end in "preparser(True)", the preparser is on all the time. If you remove the last "preparser(True)" from cell 2, then after evaluating that cell, the preparser will be off for any subsequent evaluations.

( 2012-08-30 11:48:07 -0600 )edit

You're missing some semicolons, by the way. Cell 1 should be preparser(False); print type(2); preparser(True); print type(2), and cell 2 should be preparser(True); print type(2); preparser(False); print type(2); preparser(True).

( 2012-08-30 11:49:07 -0600 )edit