简体   繁体   中英

How can I get a string(Mix of digit and char) up to last digit using regex in python?

I have strings like:

" 5473 & 4835 how to find the index"

" 5473 how to find the index"

" 5473 & A-121-2 how to find the index"

" A-121-2 how to find the index"

How can I extract the string up to last digit using regex.

For example, the result I want in above is like this:

" 5473 & 4835"

" 5473"

" 5473 & A-121-2"

" A-121-2"

Use greediness of *

^.*\d
  1. ^ asserts that we are at the start of a line.
  2. .* will greedily matches all the characters upto the last
  3. \\d and then it backtracks in-order to find a digit character.

Example:

>>> re.search(r'^.*\d', " 5473 & 4835 how to find the index").group()
' 5473 & 4835'
>>> re.search(r'^.*\d', 'A-121-2 how to find the index').group()
'A-121-2'

DEMO

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