That horrible regexp idiom

Stephen Thorne stephen.thorne at gmail.com
Thu Feb 10 02:10:57 EST 2005


Hi,

import re
foo_pattern = re.compile('foo')

'>>> m = foo_pattern.search(subject)
'>>> if m:
'>>>    pass
'>>> else:
'>>>    pass


We've all seen it before. Its a horrible idiom that you would achieve
in another language by doing:

if (m = foo_pattern.search(subject)) 
{ }
else
{ }

but it occured to me today, that it is possible to do it in python
without the extra line.
'
'>>> def xsearch(pattern, subject):
'>>>     yield pattern.search(subject)

'>>> for m in xsearch(foo_pattern, subject):
'>>>     pass
'>>> else:
'>>>     pass

simple, concise, requires no new syntax, and is only a little confusing[1]!

Just recording some thoughts I had. This still doesn't take care of
the horrors of chaining multiple regular expressions. The following is
still incredibly hideous.

'>>> for m in xsearch(foo_pattern, subject):
'>>>     pass
'>>> else:
'>>>     for m in xsearch(bar_pattern, subject):
'>>>         pass
'>>>     else:
'>>>         pass

Thankyou for your time.

Stephen Thorne

[1] Actual confusement may vary.



More information about the Python-list mailing list