Python 如何获取字符串中的最后一个数字和+;1.

Python 如何获取字符串中的最后一个数字和+;1.,python,Python,我需要在字符串中找到最后一个数字(不是一个数字),并替换为数字+1,例如:/path/testcase9.in到/path/testcase10.in。如何在python中更好或更高效地完成这项工作 以下是我现在使用的: reNumber = re.compile('(\d+)') def getNext(path): try: number = reNumber.findall(path)[-1] except: return None

我需要在字符串中找到最后一个数字(不是一个数字),并替换为
数字+1
,例如:
/path/testcase9.in
/path/testcase10.in
。如何在python中更好或更高效地完成这项工作

以下是我现在使用的:

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)))
这使用了,特别是,使“替换”成为一个函数的能力,该函数与原始匹配一起调用,以确定应该替换什么

它还使用断言来确保正则表达式仅与字符串中的最后一个数字匹配。

在re中使用“*”可以选择最后一个数字之前的所有字符(因为它是贪婪的):

结果是:

somefile10.in
some9file11.in
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)
somefile10.in
some9file11.in