处理以re.sub替换模式捕获组的反向引用

Ric*_*ard 68 python regex

我想取字符串0.71331, 52.25378并返回0.71331,52.25378- 即只需查找数字,逗号,空格和数字,并删除空格.

这是我目前的代码:

coords = '0.71331, 52.25378'
coord_re = re.sub("(\d), (\d)", "\1,\2", coords)
print coord_re
Run Code Online (Sandbox Code Playgroud)

但这给了我0.7133,2.25378.我究竟做错了什么?

And*_*ark 94

您应该使用原始字符串进行正则表达式,请尝试以下操作:

coord_re = re.sub(r"(\d), (\d)", r"\1,\2", coords)
Run Code Online (Sandbox Code Playgroud)

使用当前代码,替换字符串中的反斜杠将转义数字,因此您将替换所有匹配项,相当于chr(1) + "," + chr(2):

>>> '\1,\2'
'\x01,\x02'
>>> print '\1,\2'
,
>>> print r'\1,\2'   # this is what you actually want
\1,\2
Run Code Online (Sandbox Code Playgroud)

任何时候你想在字符串中留下反斜杠,使用r前缀,或者转义每个反斜杠(\\1,\\2).

  • 谢谢,这就是诀窍.http://docs.python.org/library/re.html#raw-string-notation适用于阅读本文的任何人. (2认同)
  • 这在 Python3 中不起作用。使用 `\1` 将其替换为一些奇怪的 unicode 字符。 (2认同)

Pet*_*rin 13

Python将其解释\1为ASCII值为1的字符,并将其传递给sub.

使用原始字符串,Python不解释它\.

coord_re = re.sub(r"(\d), (\d)", r"\1,\2", coords)
Run Code Online (Sandbox Code Playgroud)

如果您需要更多信息,请在re文档开头部分进行介绍.