2013-04-21 60 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 
相關問題