我有以下类型的字符串:
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/