I have a list like:
a = ['aaa/aa/aa/a001', 'aaa/aa/aa/a002', 'aaa/aa/aa/a003']
I want to retrieve the number part. How can I do that?
Using a list comprehension with re.sub:
a = ['aaa/aa/aa/a001','aaa/aa/aa/a002','aaa/aa/aa/a003']
out = [re.sub(r'^.*?(\d+)$', r'\1', x) for x in a]
print(out)
This prints:
['001', '002', '003']
The strategy here is to match and capture the digits at the end of each string in the list. Note that this approach is robust even if digits might also appear earlier in the string.
^.*?(\d+)\D+\d+$ and then also access the first capture group \1 as the replacement.value.split("/")[-1] first, before using your regex. That avoids numerical patterns higher up impacting what seems to concern only the leaves.