0

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"

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

Can you please tell how does this work? I am trying to learn regex
Thanks a lot. It worked. One more question: What if I have something like "No.- 12345 asbf" and I only need to get the result as "12345".
re.findall(r'\d+', string) .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.