Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #7741
| References | <itcu3f$b1k$1@speranza.aioe.org> |
|---|---|
| Date | 2011-06-16 15:25 +0200 |
| Subject | Re: Composing regex from a list |
| From | Vlastimil Brom <vlastimil.brom@gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.15.1308230734.1164.python-list@python.org> (permalink) |
2011/6/16 TheSaint <nobody@nowhere.net.no>: > 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? > In simple cases, you can just join the list of alternatives on "|" and incorporate it in the pattern - e.g. in non capturing parentheses: (?: ...) cf.: >>> >>> lst= ['good', 'brilliant', 'solid'] >>> import re >>> re.findall(r"^(?:"+"|".join(lst)+")", u"solid sample text; brilliant QWERT") [u'solid'] >>> [using findall just to show the result directly, it is not that usual with starting ^ ...] However, if there can be metacharacters like [ ] | . ? * + ... in the alternative "words", you have to use re.escape(...) on each of these before. Or you can use a newer regex implementation with more features http://pypi.python.org/pypi/regex which was just provisionally enhanced with an option for exactly this usecase: cf. Additional features: Named lists on the above page; in this case: >>> import regex # http://pypi.python.org/pypi/regex >>> regex.findall(r"^\L<options>", u"solid sample text; brilliant QWERT", options=lst) [u'solid'] >>> hth, vbr
Back to comp.lang.python | Previous | Next — Previous in thread | Find similar | Unroll thread
Composing regex from a list TheSaint <nobody@nowhere.net.no> - 2011-06-16 20:48 +0800
Re: Composing regex from a list Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-06-16 13:09 +0000
Re: Composing regex from a list TheSaint <nobody@nowhere.net.no> - 2011-06-17 19:45 +0800
Re: Composing regex from a list Vlastimil Brom <vlastimil.brom@gmail.com> - 2011-06-16 15:25 +0200
csiph-web