Python重新替代了所需的更多内容

问题描述

我正在使用Python学习正则表达式,遇到了以下问题。我们有6个字符串,需要将起始子字符串"00"替换为“ A”。

在第一个字符串^[0][0]*上使用表达式'001234',我们得到A1234的预期结果。

import re

# 1: Works fine
foo = '001234'
match = re.match(r"^[0][0][0-9]{4}$",foo)
print(match.group(0))       # 001234

bar = re.sub(r"^[0][0]*",'A',match.group(0))
print(bar)                  # A1234

但是,第二个字符串'000123'更改为A123而不是A0123

# 2: Substitutes more than needed
foo = '000123'
match = re.match(r"^[0][0][0-9]{4}$",foo)
print(match.group(0))       # 000123

bar = re.sub(r"^[0][0]*",match.group(0))
print(bar)                  # A123
                            # Expects: A0123

正则表达式模式出了什么问题,我们该如何解决

谢谢!

解决方法

您只需要在要替换的行的开头指定零的数量,

foo = '000100'
re.sub(r'^0{2}',r'A',foo)

'A0100'