Escape literal user-provided text before placing it in a regex.
How It Works
re.escape(text) adds escapes to regex metacharacters so they can be matched literally. It is appropriate for a literal pattern fragment, not for arbitrary replacement strings passed to sub().
Step-by-Step Example
import re
search_term = 'item[1]'
print(bool(re.search(re.escape(search_term), 'Find item[1] today')))
print(re.escape('a+b'))
Understanding the Example
- The expression "'item[1]'" supplies the value stored as 'search_term'. This value is then used or checked by the later statements.
- The print() call exposes the result so you can compare it with the behavior described above. Check the value and its type when experimenting.
A successful run of this example prints the following output:
True
a\+b
Where This Fits in a Real Program
Start by writing down examples that should match and examples that must fail. Check whether you need to locate a substring, match a prefix or validate an entire field; these are different operations. Unicode and escape sequences can also change which characters are matched, so test accented text and empty input.
Practice: Try It Yourself
If the goal is simple substring search, the in operator is often preferable.
For this exercise, predict the result before running the changed code. Then explain the difference between the original and modified cases using the actual values, not just whether the program completed.
Further Reading
Read the official Python documentation for complete parameters, return types and exceptions.
Common Beginner Mistakes
- Interpolating unescaped user text in a regex and accidentally changing the pattern meaning.
- Search for a literal filename containing brackets and periods.
Key Takeaways
- Escape literal user-provided text before placing it in a regex.
- re.escape(text) adds escapes to regex metacharacters so they can be matched literally.
- Apply the demonstrated operation to the practice input and verify its result before depending on it in a larger program.