更换';nnn0n';与';nnn1n';在Python中使用正则表达式
我想用更换';nnn0n';与';nnn1n';在Python中使用正则表达式,python,regex,Python,Regex,我想用'nnn1n'格式的字符串替换'nnn1n'格式的字符串,其中n是任意数字。最简单的方法是什么?到目前为止,我尝试了以下方法: int(re.sub(r'^(\d+?)(0)(\d)$', r'\1???\3', '7001')) 但是我在中插入的任何内容都会返回不正确的结果,无论是1还是\1 有什么想法吗 编辑: 我想出了一个丑陋的版本: re.sub(r'a1a', '1', re.sub(r'^(\d+?)(0)(\d)$', r'\1a1a\3', '7001')) 有更好的
'nnn1n'
格式的字符串替换'nnn1n'
格式的字符串,其中n
是任意数字。最简单的方法是什么?到目前为止,我尝试了以下方法:
int(re.sub(r'^(\d+?)(0)(\d)$', r'\1???\3', '7001'))
但是我在中插入的任何内容都会返回不正确的结果,无论是1
还是\1
有什么想法吗
编辑:
我想出了一个丑陋的版本:
re.sub(r'a1a', '1', re.sub(r'^(\d+?)(0)(\d)$', r'\1a1a\3', '7001'))
有更好的吗?您可以做以下事情:
re.sub(r'^(\d{3})0(\d)$', r'\g<1>1\2', '7001')
您可以使用一个命名的组来绕过此问题
int(re.sub(r'^(?P<prefix>\d+?)0(\d)$', r'\g<prefix>1\2', '7001'))
你真的不需要正则表达式
replace = lambda x: '{0}1{1}'.format(x[:-2], x[-1]) if x[-2] == '0' else x
# or: x[:-2] + '1' + x[-1]
print replace('12345678901')
>r=re.compile(r'(\d{3})0(\d'))
>>>r.sub('\g1\g','88808')
88818
没有regex的另一个“不太好”的解决方案-但我至少要自己尝试一下:
data = ['7001', '700001', '701', '71', '12345']
res = (int(x)+10 if len(x) > 2 and x[-2] == '0' else int(x) for x in a )
print list(res)
下面是一个数字解决方案:
def addTenNumeric(n):
"""Add 10 to n if, as decimal, the 2nd least significant digit of n is 0"""
if (n % 100) < 10:
return n + 10
return n
def addTenNumeric(n):
“”“如果n的第二个最低有效位为0,则将10添加到n”
如果(n%100)<10:
返回n+10
返回n
这应该比在字符串表示中使用正则表达式快得多。是否总是3位,1位要替换,1位?不,开头的位数可能不同,我想用1替换结尾的第二个0,以避免使用数值方法?比如加10?唯一的原因是如果10是aleady加的,但你是对的,用数值方法应该简单得多:)。是的,但正则表达式更有趣;)
replace = lambda x: '{0}1{1}'.format(x[:-2], x[-1]) if x[-2] == '0' else x
# or: x[:-2] + '1' + x[-1]
print replace('12345678901')
>>> r = re.compile(r'(\d{3})0(\d)')
>>> r.sub('\g<1>1\g<2>', '88808')
88818
data = ['7001', '700001', '701', '71', '12345']
res = (int(x)+10 if len(x) > 2 and x[-2] == '0' else int(x) for x in a )
print list(res)
def addTenNumeric(n):
"""Add 10 to n if, as decimal, the 2nd least significant digit of n is 0"""
if (n % 100) < 10:
return n + 10
return n