coder
coder

Reputation: 930

Regex, extracting both word and number at the end of a string

I'm a beginner to regex and encountered a problem and didn't find a solution, So let's say I have a string ab123cd456, I'm trying to find a regex expression that would extract the text untill the last number (if any) and the number itself so the result of the extraction would be ["ab123cd", "456"] extracting the end number is easily done by \d+$

but I am unable to make an expression to extract the ab123cd I've tried .*(?=\d+$) which extract ab123cd45 which is weird to me because + is a greedy expression

Please note that I want a single expression for the task

Upvotes: 3

Views: 736

Answers (1)

Mats Kindahl
Mats Kindahl

Reputation: 2075

You need to have a non-greedy match as the first one:

import re

lines = ["abc12cd1234"]

for line in lines:
    mre = re.match(r'(\w+?)(\d+)$', line)
    if mre:
        print mre.groups()

Will print:

('abc12cd', '1234')

Upvotes: 1

Related Questions