We have a 6 character strings that need to have the starting substring "00"
replaced with "A".
Using the expression ^[0][0]*
on the first string '001234'
, we get the expected result of 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
However, the second string '000123'
was changed to A123
instead of 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]*", 'A', match.group(0))
print(bar) # A123
# Expects: A0123
What went wrong with the regex pattern, and how can we fix it?