Composing regex from a list
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Thu Jun 16 09:09:20 EDT 2011
On Thu, 16 Jun 2011 20:48:46 +0800, TheSaint wrote:
> Hello,
> Is it possible to compile a regex by supplying a list?
>
> lst= ['good', 'brilliant'. 'solid']
>
> re.compile(r'^'(any_of_lst))
>
> without to go into a *for* cicle?
How about this?
def compile_alternatives(*args):
alternatives = map(lambda s: '(' + s + ')', args)
alternatives = '|'.join(alternatives)
return re.compile(alternatives)
>>> x = compile_alternatives('spam', 'ham', 'cheese')
>>> x.search('fried egg and spam').group()
'spam'
--
Steven
More information about the Python-list
mailing list