matching multiple regexs to a single line...

Noel Minet noel.minet at noos.fr
Tue Nov 12 18:02:18 EST 2002


You can also use a more general regex and check if a group is None

something like

>>> import re
>>> regex_set = {'digit':'\d+','lowercase':r'[a-z]+','uppercase':r'[A-Z]+'}
>>> tst = re.compile(''.join(['(?P<%s>^%s$)?'%r for r in
regex_set.items()]))
>>>
>>> m = tst.match('1234')
>>> m.group('digit')
'1234'
>>> m.group('uppercase')
>>> m.group('lowercase')
>>>
>>> m = tst.match('UPPER')
>>> m.group('digit')
>>> m.group('uppercase')
'UPPER'
>>> m.group('lowercase')
>>>
>>> m = tst.match('lower')
>>> m.group('digit')
>>> m.group('uppercase')
>>> m.group('lowercase')
'lower'
>>>
>>> m = tst.match('Mixed')
>>> m.group('digit')
>>> m.group('uppercase')
>>> m.group('lowercase')
>>>

The drawback is that you compile all regexes

HTH


"Alexander Sendzimir" <lists at battleface.com> wrote in message
news:pan.2002.11.12.20.44.22.748716 at battleface.com...
> John,
>
> Thanks for your response. This is what I was afraid of. This seems really
> sloppy. You don't think there is any better way of doing such a thing? In
> the mean time, what you propose is exactly what I've been doing. Hmmmm.
>
> Alex
>
>
>
> On Tue, 12 Nov 2002 15:18:01 +0000, John Hunter wrote:
> >
> > That's what I usually end up doing
> >
> > for line in myfile:
> >   m = r1.match(line)
> >   if m:
> >     do_something()
> >     break
> >
> >   m = r2.match(line)
> >   if m:
> >     do_something_else()
> >     break
> >
> >
> > John Hunter
>





More information about the Python-list mailing list