abcdabcd987
abcdabcd987

Reputation: 2053

How to get the last number in a string and +1?

I need to find the last number occurrence (not a single digit) in a string, and replace with number+1, for example: /path/testcase9.in to /path/testcase10.in. How to do this in python more nicely or efficiently?

Here is what I am using now:

reNumber = re.compile('(\d+)')

def getNext(path):
    try:
        number = reNumber.findall(path)[-1]
    except:
        return None
    pos = path.rfind(number)
    return path[:pos] + path[pos:].replace(number, str(int(number)+1))

path = '/path/testcase9.in'
print(path + " => " + repr(self.getNext(path)))

Upvotes: 1

Views: 161

Answers (2)

tstone2077
tstone2077

Reputation: 514

by using ".*" in your re, you can select all characters before the last digit (since it's greedy):

import re

numRE = re.compile('(.*)(\d+)(.*)')

test = 'somefile9.in'
test2 = 'some9file10.in'

m = numRE.match(test)
if m:
    newFile = "%s%d%s"%(m.group(1),int(m.group(2))+1,m.group(3))
    print(newFile)

m = numRE.match(test2)
if m:
    newFile = "%s%d%s"%(m.group(1),int(m.group(2))+1,m.group(3))
    print(newFile)

The result is:

somefile10.in
some9file11.in

Upvotes: 0

Amber
Amber

Reputation: 526593

LAST_NUMBER = re.compile(r'(\d+)(?!.*\d)')

def getNext(path):
    return LAST_NUMBER.sub(lambda match: str(int(match.group(1))+1), path)

This uses re.sub and in particular, the ability to have the "replacement" be a function that's called with the original match to determine what should replace it.

It also uses a negative lookahead assertion to make sure the regex only matches the last number in the string.

Upvotes: 3

Related Questions