HeelMega
HeelMega

Reputation: 508

Search string by regex and increment it by 1

I have a string as follows:

desc = "Testing 1.1.1.1"

I would like to find the version number at the end of the string and increment it by 1.

I am able to search and get the string by regex but I am not sure how to increment it by 1 on the fly. Any help will be appreciated.

import re

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

Upvotes: 0

Views: 250

Answers (1)

Mark Tolonen
Mark Tolonen

Reputation: 177685

The replacement in re.sub can be a function. The function receives the match object from the regular expression. Here's one way to do it (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)

Output:

Testing 1.1.1.2

Upvotes: 1

Related Questions