RE Module

Fredrik Lundh fredrik at pythonware.com
Fri Aug 25 17:58:16 EDT 2006


tobiah wrote:

> Also, how does the engine decide whether I am adjusting
> the greed of the previous operator, or just asking
> for another possible character?

"?" always modifies the *preceeding* RE element.

if the preceeding element is a pattern (e.g. a character or group), it 
means that the pattern is optional.

if the preceeding element is a repeat modifier (*, +, or ?), it changes 
the greediness.

> Suppose I want:
> 
> 	"x*?" to match "xxxxxxxO"
> 
> If the '?' means non greedy, then I should get 'x' back.

no, because "*" means *ZERO* or more matches, not one or more.

> If the '?' means optional character then I should get
> the full string back.

no, because "?" never means anything on its own; it's a pattern 
modifier, not a pattern.

> Checking in python:
> 
> ######################################
> import re
> 
> s = 'xxxxxxx0'
> 
> m = re.search("x*", s)
> print "First way", m.group(0)
> 
> m = re.search("x*?", s)
> print "Second way", m.group(0)
> #####################################
> First way xxxxxxx
> Second way
> 
> So now I'm really confused.  It didn't do a non-greedy
> 'x' match, nor did it allow the '?' to match the '0'.

see above.  reading the RE documentation again may also help.

</F>




More information about the Python-list mailing list