使用正则表达式添加前导零 [英] Using regex to add leading zeroes

查看:224
本文介绍了使用正则表达式添加前导零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在字符串的所有数字上添加一定数量的前导零(例如最多3个).例如:

I would like to add a certain number of leading zeroes (say up to 3) to all numbers of a string. For example:

输入:/2009/5/song 01 of 12

输出:/2009/0005/song 0001 of 0012

使用正则表达式执行此操作的最佳方法是什么?

What's the best way to do this with regular expressions?

我选择了第一个正确答案.但是,所有答案都值得一读.

I picked the first correct answer. However, all answers are worth giving a read.

推荐答案

使用支持回调的内容,以便您处理匹配:

Use something that supports a callback so you can process the match:

>>> r=re.compile(r'(?:^|(?<=[^0-9]))([0-9]{1,3})(?=$|[^0-9])')
>>> r.sub(lambda x: '%04d' % (int(x.group(1)),), 'dfbg345gf345', sys.maxint)
'dfbg0345gf0345'
>>> r.sub(lambda x: '%04d' % (int(x.group(1)),), '1x11x111x', sys.maxint)
'0001x0011x0111x'
>>> r.sub(lambda x: '%04d' % (int(x.group(1)),), 'x1x11x111x', sys.maxint)
'x0001x0011x0111x'

这篇关于使用正则表达式添加前导零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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