Distinguish searching anywhere from matching a prefix and validating an entire string.
How It Works
re.search() scans until it finds a match; prefix matching checks only the start; fullmatch() requires the whole text. Choose the behavior first, then write the pattern. In versions before 3.15, re.match() is the corresponding start-of-string API.
From version 3.15, re.prefixmatch() gives start-of-string behavior an explicit name.
Step-by-Step Example
import re
pattern = r"ID-\d+"
text = "Order ID-42 complete"
print(bool(re.search(pattern, text)))
print(bool(re.match(pattern, text)))
print(bool(re.fullmatch(pattern, text)))
Understanding the Example
- The expression 'r"ID-\\d+"' supplies the value stored as 'pattern'. This value is then used or checked by the later statements.
- The expression '"Order ID-42 complete"' supplies the value stored as 'text'. This value is then used or checked by the later statements.
A successful run of this example prints the following output:
True
False
False
Where This Fits in a Real Program
A practical archive workflow has separate decisions for selection, compression, extraction and verification. When files come from other people, inspect paths, member counts and uncompressed sizes before writing anything; a successful decompression does not establish that its contents are trustworthy.
Practice: Try It Yourself
Test ID-42, Prefix ID-42 and ID-42 extra with all three approaches.
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
- Using re.search() to validate an entire identifier and accepting unwanted surrounding text.
- Expecting a prefix matcher to find a pattern in the middle of the string.
Key Takeaways
- Distinguish searching anywhere from matching a prefix and validating an entire string.
- re.search() scans until it finds a match; prefix matching checks only the start; fullmatch() requires the whole text.
- From version 3.15, re.prefixmatch() gives start-of-string behavior an explicit name.