【发布时间】:2014-08-22 16:09:12
【问题描述】:
在 python 2.7 和模块 re
我有这个字符串
cat description:
cat age: 10
cat size: 20
other properties
end cat description:
我试着得到
cat description:
cat age: 30
cat size: 40
other properties
end cat description:
为此我尝试
pattern = re.compile(
(
r"(cat description.*cat age: )\d+"
"(.*cat size: )\d+"
"(.*end cat description:)"
),
re.MULTILINE
)
age = '30'
size = '40'
return pattern.sub(
r"\1{}\2{}\3".format(age, size),
cat_string_description
)
但是,我明白了
“错误:无效组引用”
如果我尝试
return pattern.sub(
r"\1\2\3",
cat_string_description
)
我明白了
cat description:
cat age:
cat size:
other properties
end cat description:
为什么我得到error: invalid group reference?
【问题讨论】:
-
@OlehPrypin python 2.7
-
您获得了无效的组引用,因为
r"\1{}\2{}\3".format('30', '40') -> '\\130\\240\\3'并且您没有组号130也没有编号240。
标签: python regex python-2.7