解决正则表达式警告:DeprecationWarning: invalid escape sequence

注意,正则匹配时,最好是使用r"\d""\\d"而不只是"\d",虽然使用"\d"可以达到预期效果,但是会报警告DeprecationWarning: invalid escape sequence '\d'。因为反斜杠会被理解为转义字符,而未识别的转义字符不同于C语言直接报错,而会被保持在字符串内。
自Python3.6,未识别的转义字符会产生DeprecationWarning;自Python3.12,这会产生SyntaxWarning;最终,在未来的Python版本里会产生SyntaxError

下面节选自Python官方文档原文:

Unlike Standard C, all unrecognized escape sequences are left in the string unchanged, i.e., the backslash is left in the result. (This behavior is useful when debugging: if an escape sequence is mistyped, the resulting output is more easily recognized as broken.) It is also important to note that the escape sequences only recognized in string literals fall into the category of unrecognized escapes for bytes literals.

Changed in version 3.6: Unrecognized escape sequences produce a DeprecationWarning.

Changed in version 3.12: Unrecognized escape sequences produce a SyntaxWarning. In a future Python version they will be eventually a SyntaxError.

文档链接

你可能感兴趣的:(正则表达式,python)