3 回答
TA贡献1829条经验 获得超7个赞
使用整数加法?
def increment(match):
# convert the four matches to integers
a,b,c,d = [int(x) for x in match.groups()]
*a,b,c,d = [int(x) for x in str(a*1000 + b*100 + c*10 + d + 1)]
a = ''.join(map(str,a)) # fix for 2 digit 'a'
# return the replacement string
return f'{a}.{b}.{c}.{d}'
TA贡献1785条经验 获得超4个赞
如果您的版本永远不会超过 10,最好将其转换为整数,将其递增,然后再转换回字符串。这允许您根据需要增加尽可能多的版本号,并且不限于数千个。
def increment(match):
match = match.replace('.', '')
match = int(match)
match += 1
match = str(match)
output = '.'.join(match)
return output
TA贡献2003条经验 获得超2个赞
添加1到最后一个元素。如果大于9,则将其设置0为并对前一个元素执行相同操作。根据需要重复:
import re
def increment(match):
# convert the four matches to integers
g = [int(x) for x in match.groups()]
# increment, last one first
pos = len(g)-1
g[pos] += 1
while pos > 0:
if g[pos] > 9:
g[pos] = 0
pos -= 1
g[pos] += 1
else:
break
# return the replacement string
return '.'.join(str(x) for x in g)
print (re.sub(r"\b(\d+)\.(\d+)\.(\d+)\.(\d+)\b", increment, '1.8.9.9'))
print (re.sub(r"\b(\d+)\.(\d+)\.(\d+)\.(\d+)\b", increment, '1.9.9.9'))
print (re.sub(r"\b(\d+)\.(\d+)\.(\d+)\.(\d+)\b", increment, '9.9.9.9'))
结果:
1.9.0.0
2.0.0.0
10.0.0.0
添加回答
举报