For the string itself, just search and use the latter:
import re st='123456 nn1 nn2 nn3 nn4 mlm nn5 mlm' print re.findall(r'(nn\d+)',st)[-1]
Print nn5
You can also do the same using finditer , which makes it easier to find the appropriate indexes:
print [(m.group(),m.start(),m.end()) for m in re.finditer(r'(nn\d+)',st)][-1]
Printing ('nn5', 27, 30)
If you have many matches and want only the latter, sometimes it makes sense to just change the line and pattern:
m=re.search(r'(\d+nn)',st[::-1]) offset=m.start(1) print st[-m.start(1)-len(m.group(1)):-m.start(1)]
Print nn5
dawg
source share