YANRQ (yet another regex question)

Mats Kindahl matkin at iar.se
Fri Mar 15 04:47:34 EST 2002


Michael George Lerner <mlerner at asteroids.gpcc.itd.umich.edu> writes:

> I wanted to match this:
> 
> (?P<foo>foo    | foo   |  foo  |   foo |    foo)
> 
> without typing in all of the different combinations of 'foo' and spaces.
> 
> (Tim kindly pointed out the typos in the above, which I've corrected)
> 
> Mats Kindahl <matkin at iar.se> wrote:
> 
> > Depending on the definition of easy, this is the alternative I would
> > use. 
> 
> > 	r = re.compile(r'(?P<foo>(?=.{7}) *foo *)')
> > 	
> > Of course, your milage may wary.
> 
> Doesn't quite work for me:
> 
> >>> import re
> >>> r = re.compile(r'(?P<foo>(?=.{7}) *foo *)')
> >>> s = r.match('foo         ').groupdict()['foo']
> >>> s
> 'foo         '
> >>> len(s)
> 12
> >>> 
> 
> and I only want to match things that are seven characters long here.

That's what I get for not reading the manual... :/

Of course it should be

    r = re.compile(r'(?P<foo>(?=.{7}$) *foo *)')
                                    ^
                                    !
                                    +-- notice missing dollar

-- 
Mats Kindahl, IAR Systems, Sweden

Any opinions expressed are my own, not my company's.



More information about the Python-list mailing list