Python 弃用警告:无效的转义序列 - 用什么代替 \d?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50504500/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:30:52  来源:igfitidea点击:

DeprecationWarning: invalid escape sequence - what to use instead of \d?

pythonregexpython-3.x

提问by mchfrnc

I've met a problem with remodule in Python 3.6.5. I have this pattern in my regular expression:

re在 Python 3.6.5 中遇到了模块问题。我的正则表达式中有这个模式:

'\nRevision: (\d+)\n'

But when I run it, I'm getting a DeprecationWarning.

但是当我运行它时,我得到了一个DeprecationWarning.

I searched for the problem on SO, and haven't found the answer, actually - what should I use instead of \d+? Just [0-9]+or maybe something else?

在 SO 上搜索了这个问题,实际上还没有找到答案 - 我应该用什么来代替\d+?只是[0-9]+或者别的什么?

回答by ACascarino

Python 3 interprets string literals as Unicode strings, and therefore your \dis treated as an escaped Unicode character.

Python 3 将字符串文字解释为 Unicode 字符串,因此您将\d被视为转义的 Unicode 字符。

Declare your RegEx pattern as a raw string instead by prepending r, as below:

将您的 RegEx 模式声明为原始字符串,而不是在前面加上r,如下所示:

r'\nRevision: (\d+)\n'

This also means you can drop the escapes for \nas well since these will just be parsed as newline characters by re.

这也意味着您也可以删除转义\n符,因为它们只会被re.