除了这两种方法,我正在寻找其他的解决方式:
# match last occurence of \d+, 24242 in this case
>>> test = "123_4242_24242lj.:"
>>> obj = re.search(r"\d+(?!.*\d)", test)
>>> obj.group()
'24242'
>>> re.findall(r"\d+", test)[-1]
'24242'
findall()
。re.findall(r"\d+", test)[-1]
...干净、简洁且立即明显。
\d+(?=\D*$)
>>> import re
>>> test = "123_4242_24242lj.:"
>>> print re.findall(r'(\d+)\D*$', test)
['24242']
>>>
。其中包含替代:
>>> re.sub(r'.*?(\d+)\D*$', "\\1", test)
'24242'
re.compile
来编译它。 - thefourtheye