DeprecationWarning:无效的转义序列-使用什么代替\ d?

问题:DeprecationWarning:无效的转义序列-使用什么代替\ d?

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

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

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

在SO上搜索了问题,但没有找到答案,实际上-我应该用什么代替\d+?只是[0-9]+还是其他?

I’ve met a problem with re module in Python 3.6.5. I have this pattern in my regular expression:

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

But when I run it, I’m getting a 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?


回答 0

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

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

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

这也意味着您也可以删除转义\n符,因为这些转义符仅会被解析为换行符re

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

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

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

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