Change matching behavior using regular-expression flags.
How It Works
re.IGNORECASE handles case-insensitive matching, MULTILINE changes ^ and $ line boundaries, and DOTALL lets dot match newline characters. Combine flags with the bitwise OR operator.
Step-by-Step Example
import re
message = 'alpha\nBETA'
print(re.findall(r'^beta', message, re.IGNORECASE | re.MULTILINE))
print(bool(re.search(r'alpha.*BETA', message, re.DOTALL)))
Understanding the Example
- The expression "'alpha\\nBETA'" supplies the value stored as 'message'. 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:
['BETA']
True
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
Some Unicode case-matching behavior differs from ASCII-only matching.
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
- Assuming MULTILINE makes dot match newline characters; that requires DOTALL.
- Find case-insensitive log levels at the beginning of each line.
Key Takeaways
- Change matching behavior using regular-expression flags.
- re.IGNORECASE handles case-insensitive matching, MULTILINE changes ^ and $ line boundaries, and DOTALL lets dot match newline characters.
- Apply the demonstrated operation to the practice input and verify its result before depending on it in a larger program.