Python 正则表达式 : How to increase only one number in string?

标签 python regex

我有以下类型的字符串:

a1 = 'images1subimages1/folder100/hello1.png'
a1 = 'images1subimages1 folder100 hello1.png'
a1 = 'images1subimages1folder100hello1.png'
a1 = 'images1b100d1.png'

字符串的第一个整数是num0,我们只关心它。我们希望将 num0 的所有出现次数增加一次,并保持其他数字相同。

必需:

a2 = 'images2subimages2/folder100/hello2.png'
a2 = 'images2subimages2 folder100 hello2.png'
a2 = 'images2subimages2folder100hello2.png'
a2 = 'images2b100d2.png'

我的尝试:

import re
a1 = 'images1subimages1/folder100/hello1.png'

nums = list(map(int, re.findall(r'\d+', a1)))
nums0 = nums[0]
nums_changed = [j+1  if j==nums[0] else j for i,j in enumerate(nums)]
parts = re.findall(r'(\w*\d+)',a1)
for i in range(len(parts)):
  num_parts = list(map(int, re.findall(r'\d+', parts[i])))
  for num_part in num_parts:
    if num_part == nums0:
        parts[i] = parts[i].replace(str(nums0), str(nums0+1))


ans = '/'.join(parts)
ans

结果如下:

a1 = 'images1subimages1/folder100/hello1.png' # good
a1 = 'images1subimages1 folder100 hello1.png' # bad

有没有通用的方法可以解决在python中使用正则表达式的问题?

最佳答案

Ì 建议首先提取第一个数字,然后在没有用 re.sub 包含其他数字时递增该数字的所有出现:

import re
a1 = 'images1subimages1/folder100/hello1.png'
num0_m = re.search(r'\d+', a1)                  # Extract the first chunk of 1+ digits
if num0_m:                                      # If there is a match
    rx = r'(?<!\d){}(?!\d)'.format(num0_m.group())  # Set a regex to match the number when not inside other digits
    print(re.sub(rx, lambda x: str(int(x.group())+1), a1)) # Increment the matched numbers
    # => images2subimages2/folder100/hello2.png

参见 Python demo

关于Python 正则表达式 : How to increase only one number in string?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55461769/

相关文章:

python - 如何在 Pandas Python 中将 reset_index 与多分组值(分层格式)一起使用

python - 在 Python 中绑定(bind)信号处理程序时,<Finalize object, dead> 中没有属性 '_popen'“

javascript - 解析 VB 代码以获取注释

regex - 在文件中找到正则表达式的第一个匹配项,并打印它

用于 Laravel 验证的仅接受单词或字母的正则表达式组合

python - 玛雅/ python : How do I scale multiple selected animation curves each from their own specific pivot point?

python - 在 Python 2 中按定义顺序迭代枚举

python - Pandas 数据框计算

php - 优化句子清理器的正则表达式

javascript - 如何替换 JavaScript 正则表达式中的冒号和星号特殊字符