YANRQ (yet another regex question)
Mats Kindahl
matkin at iar.se
Thu Mar 14 06:16:36 EST 2002
Tim Peters <tim.one at comcast.net> writes:
> [Michael George Lerner]
> > I have a regular expression that looks vaguely like this:
> >
> > r = re.compile(r'''(?P<start>start)(?P<foo> foo)(?P<end>end)''')
> >
> > but the middle pattern isn't quite what I want. I know that foo
> > will be a string that is seven characters long and contains 'foo'
> > surrounded by spaces. That is, it could be any of these:
> >
> > 'foo '
> > ' foo '
> > ' foo '
> > ' foo '
> > ' foo'
> >
> > I'd like to rewrite my regular expression to match any of these,
> > and I'd really rather not write it all out like this:
> >
> > (?P<foo>(foo | foo | foo | foo | foo|)
>
> That will also match an empty string (remove the last vertical bar; ditto
> the 2nd left paren).
>
> > Is there some easy way to do this that I've overlooked?
>
> You already found an easy way <wink>. If you ask whether there's an easier
> way, the answer is no.
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.
--
Mats Kindahl, IAR Systems, Sweden
Any opinions expressed are my own, not my company's.
More information about the Python-list
mailing list