2013-04-21 61 views
1

我需要找到字符串中的最后一个数字(不是一个数字),并用number+1替换,例如:/path/testcase9.in/path/testcase10.in。如何更好地或有效地在Python中做到这一点?如何获取字符串中的最后一个数字和+1?

这里是我使用的是什么现在:

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))) 

回答

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

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

这使用re.sub,特别是,有“更新换代”的能力是一个与原来的比赛叫,以确定哪些应该功能代替它。

它也使用negative lookahead断言来确保正则表达式只匹配字符串中的最后一个数字。 “*”

0
在你重新

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

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 
相关问题