Python正则表达式:如何只增加字符串中的一个数字? [英] Python regex: How to increase only one number in string?

查看:58
本文介绍了Python正则表达式:如何只增加字符串中的一个数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下类型的字符串:

I have a string of following types:

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

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

The first Integer of the string is num0 and we only care about it. We want to increase all occurrence of num0 by one and keep other numbers the same.

必填:

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中使用正则表达式有没有通用的方法可以解决这个问题?

Is there a general way to solve the problem using regex in python?

推荐答案

Ì 建议先提取第一个数字,然后在没有用 re.sub:

Ì suggest first extracting the first number and then increment all occurrences of this number when it is not enclosed with other digits with 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 演示

这篇关于Python正则表达式:如何只增加字符串中的一个数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆