"Ben Wolfson" <wolfson at uchicago.edu> wrote in message news:dWmE6.638$E4.25725 at uchinews... > In article <roy-D0E658.17013521042001 at news.panix.com>, "Roy Smith" > <roy at panix.com> wrote: > > > What if I want to execute different code depending on which expression I > > matched? Something along the lines of (pseudocode): > > > > if (m = e1.match(line)): > > text1 = m.group(1) > > do_complicated_processing (text1) > > elif (m = e2.match(line)): [snip] > re_dispatch = {re.compile(blah):meaningful_name_1, > re.compile(durh):meaningful_name_2 > ..etc > } > for re, func in re_dispatch.items(): Dictionaries have no guaranteed order, so, if the line can match more than one re, it will be 'random' which one gets matched. In general, you're better off with a sequence of pairs, where you control the order: re_dispatch = ( (re.compile(blah), meaningful_name_1), (re.compile(durh), meaningful_name_2)) for re, func in re_dispatch: Here you don't really need the dictionary's functionality anyway, just a sequence of re->function pairs, so you might as well use it even when order of re attempted is not significant (it often is -- if not for correctness, as when more than one re may match, then maybe for speed, as trying likely-matching and/or simpler re's first may make things faster). Alex
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4