Alex Rivera | Logout

Find last match with python regular expression

Asked 2010-05-10T11:20:12.227
40

I want to match the last occurrence of a simple pattern in a string, e.g.

list = re.findall(r"\w+ AAAA \w+", "foo bar AAAA foo2 AAAA bar2")
print "last match: ", list[len(list)-1]

However, if the string is very long, a huge list of matches is generated. Is there a more direct way to match the second occurrence of " AAAA ", or should I use this workaround?

Edit
Report

1 Answer

34

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

Your Answer