This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Invalid expression error if a regex ends with a backslash
Type: behavior Stage: resolved
Components: Regular Expressions Versions: Python 2.7
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: ezio.melotti Nosy List: ezio.melotti, mlesniew
Priority: normal Keywords:

Created on 2011-11-15 19:01 by mlesniew, last changed 2022-04-11 14:57 by admin. This issue is now closed.

Messages (2)
msg147696 - (view) Author: Michał Leśniewski (mlesniew) Date: 2011-11-15 19:01
If a regular expression ends with a backslash, an exception is raised. Of course, the backslash has to be escaped. The simplest example, that causes the error is a regular expression, that should match only a single backslash:

    import re
    r = re.compile("\\")
msg147697 - (view) Author: Ezio Melotti (ezio.melotti) * (Python committer) Date: 2011-11-15 19:16
You either have to double escape it (once for python and then for the regex engine) or use raw strings:
>>> re.match("\\\\", '\\').group()
'\\'
>>> re.match(r"\\", '\\').group()
'\\'
History
Date User Action Args
2022-04-11 14:57:23adminsetgithub: 57618
2011-11-15 19:16:18ezio.melottisetstatus: open -> closed
messages: + msg147697

assignee: ezio.melotti
resolution: not a bug
stage: resolved
2011-11-15 19:01:05mlesniewcreate