You can avoid the building of a list just by iterating over all matches and keeping the last match:
def match_last(orig_string, re_prefix, re_suffix):
# first use positive-lookahead for the regex suffix
re_lookahead= re.compile(f"{re_prefix}(?={re_suffix})")
match= None
# then keep the last match
for match in re_lookahead.finditer(orig_string):
pass
if match:
# now we return the proper match
# first compile the proper regex…
re_complete= re.compile(re_prefix + re_suffix)
# …because the known start offset of the last match
# can be supplied to re_complete.match
return re_complete.match(orig_string, match.start())
return match
After this, match holds either the last match or None.
This works for all combinations of pattern and searched string, as long as any possibly-overlapping regex parts are provided as re_suffix ; in this case, \w+.
>>> match_last(
"foo bar AAAA foo2 AAAA bar2",
r"\w+ AAAA ", r"\w+")
<re.Match object; span=(13, 27), match='foo2 AAAA bar2'>
answered 2010-06-07T10:28:38.420