regexp compilation error

O

Ovidiu Deac

I have the following regexp which fails to compile. Can somebody explain why?
re.compile(r"""^(?: [^y]* )*""", re.X)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/re.py", line 190, in compile
return _compile(pattern, flags)
File "/usr/lib/python2.6/re.py", line 245, in _compile
raise error, v # invalid expression
sre_constants.error: nothing to repeat

Is this a bug or a feature?

Thanks,
Ovidiu
 
H

Hans Mulder

I have the following regexp which fails to compile. Can somebody explain why?
re.compile(r"""^(?: [^y]* )*""", re.X)
[...]
sre_constants.error: nothing to repeat

Is this a bug or a feature?

A feature: the message explains why this pattern is not allowed.

The sub-pattern (?: [^y]* ) matches zero or more non-'y's, so
it potentially matches the empty string. It you were allowed
to apply '*' to such a sub-pattern, the matcher could go into
an infinite loop, finding billions of matching empty strings,
one after the other.

I'm not sure what you are trying to match, but for zero-or-more
not-'y's, you could write r"^[^y]*". This is guaranteed to
always match, since there are always at least zero of them.

You might as well write r"^", that is also guaranteed to
always match.

What are you trying to achieve?

-- HansM
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top