【问题标题】:python regex : .format(string) in .sub with grouppython 正则表达式:.sub 中的 .format(string) 和组
【发布时间】: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


【解决方案1】:

我解决了

return pattern.sub(
    r"\g<1>{}\g<2>{}\g<3>".format('30', '40'),
    cat_string_description
)

【讨论】:

  • 你为什么打电话给.format?你可以这样做:r"\g&lt;1&gt;30&lt;2&gt;40\g&lt;3&gt;
  • 因为3040 是变量。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多