通过正则表达式搜索字符串,并将其递增1

时间:2018-12-24 05:22:53

标签: python arrays regex python-3.x string

我有一个字符串如下:

desc = "Testing 1.1.1.1"

我想在字符串末尾找到版本号,并将其递增1。

我能够通过正则表达式搜索并获取字符串,但是我不确定如何动态地将其增加1。任何帮助将不胜感激。

import re

line = re.sub(r"\b\d{1}\.\d{1}\.\d{1}\.\d{1}\b", "", line)
print(line)

1 个答案:

答案 0 :(得分:1)

re.sub中的替换项可以是一个函数。该函数从正则表达式接收匹配对象。这是一种实现方法(Python 3.6及更高版本):

import re

line = 'Testing 1.1.1.1'

def func(match):
    # convert the four matches to integers
    a,b,c,d = [int(x) for x in match.groups()]
    # return the replacement string
    return f'{a}.{b}.{c}.{d+1}'

line = re.sub(r'\b(\d+)\.(\d+)\.(\d+)\.(\d+)\b', func, line)
print(line)

输出:

Testing 1.1.1.2
相关问题