简体   繁体   中英

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'

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.

这个基于前瞻性的正则表达式匹配字符串中的最后一位数字:

\d+(?=\D*$)

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM