Skip to content Skip to sidebar Skip to footer

Invalid Value After Matching String Using Regex

I am trying to match strings with an addition of 1 at the end of it and my code gives me this problem: abcd01 should become abcde02 but my code gives me this output: abcde2 foobar

Solution 1:

Count the number of zeros until the first number and add them to the number at last. Here is the full code:

defincrement_string(strng):
    regex = re.compile(r'[0-9]')
    match = regex.findall(strng)

    nums = ''.join(match[-3:])
    strng = strng.replace(nums, '')
    iflen(nums) > 0:
        add = int(nums) + 1
        zeros = 0for digit instr(nums[:-1]):
            if digit == "0":
                zeros += 1else:
                break
        zeros -= len(str(add)) - len(str(add-1))
        add = ''.join(["0"for x inrange(zeros)]) + str(add)
    else:
        add = "1"print(strng + add)

Output:

abcd02

For foobar00:

increment_string('foobar00')

Output:

foobar01

For foobar002:

increment_string('foobar002')

Output:

foobar003

For abcd:

increment_string('abcd')

Output:

abcd1

Post a Comment for "Invalid Value After Matching String Using Regex"