Doing both regex match and assignment within a If loop?
neilc at norwich.edu
Fri Mar 29 13:51:17 CET 2013
On 2013-03-29, Alain Ketterlin <alain at dpt-info.u-strasbg.fr> wrote:
> Victor Hooi <victorhooi at gmail.com> writes:
>> expression1 = re.compile(r'....')
>> expression2 = re.compile(r'....')
> Just a quick remark: regular expressions are pretty powerful at
> representing alternatives. You could just stick everything
> inside a single re, as in '...|...'
> Then use the returned match to check which alternative was
> recognized (make sure you have at least one group in each
Yes, but in a Python program it's more straightforward to program
in Python. ;)
But this is from a grade A regex avoider, so take it with a small
chunk of sodium.
>> Is it possible to somehow test for a match, as well as do assignment
>> of the re match object to a variable?
One way to attack this problem that's not yet been explicitly
mentioned is to match using a generator function:
def match_each(s, re_seq):
for r in re_seq:
And later something like:
for match in match_each(s, (expression1, expression2, expression3)):
print(match.groups()) # etc...
More information about the Python-list