How to Fix re.error: bad escape in Python
In this tutorial, you'll learn about How to Fix re.error: bad escape in Python. We cover key concepts, practical examples, and best practices.
Python raises re.error: bad escape when a regular expression pattern contains an invalid backslash escape sequence like \c or \x.
The Wrong Way
import re
pattern = r"\d+\.\d+\.\d+\.\d+\z"
text = "192.168.1.1"
match = re.match(pattern, text)
This produces:
Traceback (most recent call last):
File "script.py", line 3, in <module>
match = re.match(pattern, text)
File "/usr/lib/python3.10/re.py", line 192, in _compile
raise re.error: bad escape \z at position 19
The Right Way
Use valid escape sequences. Replace \z with $:
import re
pattern = r"\d+\.\d+\.\d+\.\d+$"
text = "192.168.1.1"
match = re.match(pattern, text)
if match:
print("Match found:", match.group())
Output:
Match found: 192.168.1.1
Step-by-Step Fix
1. Use raw strings for regex patterns
import re
# Wrong -- \d is interpreted as a raw character
pattern = "\d+" # Python sees \d as an unknown escape
# Right -- raw string preserves backslashes
pattern = r"\d+"
2. Check escape sequence validity
Valid Python regex escapes: \d, \D, \w, \W, \s, \S, \b, \B, \A, \Z, \g<name>, \1-\99. Invalid ones like \c, \z, \e raise errors.
3. Escape literal backslashes properly
import re
# Wrong -- trying to match a literal backslash
pattern = r"\n" # matches newline, not backslash-n
# Right -- double backslash for literal backslash
pattern = r"\\n"
print(re.match(pattern, "\\n"))
4. Use re.escape() for literal text
import re
text_to_find = "price: $10.00"
pattern = re.escape(text_to_find)
print(pattern)
# Output: price\:\ \$10\.00
Prevention Tips
- Always use raw strings (
r"...") for regex patterns. - Use
re.escape()to safely include literal text in patterns. - Test regex patterns on sites like regex101.com before using them in code.
- Use
re.compile()withre.VERBOSEfor complex patterns with comments. - Avoid over-escaping -- only use
\before special regex characters.
Common Mistakes with regex error
- Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists
These mistakes appear frequently in real-world PYTHON code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro