繁体   English   中英

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

[英]Using re.sub to replace numeric part of string, with arithmetic manipulation of that number in 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'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM