laike9m
laike9m

Reputation: 19318

regex match last occurrence

I'm trying to find ways to do it other than these two:

# 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'

Upvotes: 3

Views: 296

Answers (3)

devnull
devnull

Reputation: 123458

I'm trying to find ways to do it other than these two:

A slight modification to your first approach. Capture the digits followed by anything that is not a digit at the end of the string.

>>> import re
>>> test = "123_4242_24242lj.:"
>>> print re.findall(r'(\d+)\D*$', test)
['24242']
>>>

Another alternate would be to substitute:

>>> re.sub(r'.*?(\d+)\D*$', "\\1", test)
'24242'

Upvotes: 1

salezica
salezica

Reputation: 76899

I'm sure you can find more clever regular expressions that will do this, but I think you should stick with findall().

Regular expressions are hard to read. Not just by others: let 10 days go by since the time you wrote one, and you'll find it hard to read too. This makes them hard to maintain.

Unless performance is critical, it's always best to minimize the work done by regular expressions. This line...

re.findall(r"\d+", test)[-1]

... is clean, concise and immediately obvious.

Upvotes: 2

anubhava
anubhava

Reputation: 784948

This lookahead based regex matches last digits in a string:

\d+(?=\D*$)

Upvotes: 1

Related Questions