使用re.sub替换字符串的数字部分,并在Python中对该数字进行算术运算?

问题描述

假设我有一个字符串testing-1-6-180-在这里我想捕获第二个数字(无论它是什么),在这里它是“ 6”,然后我想在其数字值上加上5(因此6),然后输出字符串-因此,在这种情况下,结果应为testing-1-11-180

这是我到目前为止尝试过的:

import re

mytext = "testing-1-6-180"
pat_a = re.compile(r'testing-1-(\d+)')
result = pat_a.sub( "testing-1-{}".format( int('\1')+5 ),mytext )

...不幸的是,此操作失败并显示

$ python3 test.py
Traceback (most recent call last):
  File "test.py",line 7,in <module>
    result = pat_a.sub( "testing-1-{}".format( int('\1')+5 ),mytext )
ValueError: invalid literal for int() with base 10: '\x01'

那么,如何获取捕获的反向引用,以便将其转换为int并进行一些算术运算,然后使用结果替换匹配的子字符串?


能够很好地发布答案会很高兴,因为在这里找出如何将答案应用于此问题并不是一件容易的事,但是无论如何没人在乎,所以我将答案发布为编辑:

import re

mytext = "testing-1-6-180"
pat_a = re.compile(r'testing-1-(\d+)')

def numrepl(matchobj):
  return "testing-1-{}".format( int(matchobj.group(1))+5 )

result = pat_a.sub( numrepl,mytext )
print(result)

结果为testing-1-11-180

解决方法

您可以使用lambda代替:

>>> mytext = "testing-1-6-180"
>>> s = re.sub(r'^(\D*\d+\D+)(\d+)',lambda m: m.group(1) + str(int(m.group(2)) + 5),mytext)
>>> print (s)
'testing-1-11-180'