Collect all nonoverlapping regex matches as a list.
How It Works
re.findall(pattern, string) returns strings when there are no capture groups, group strings when one group exists, and tuples when several groups exist. It may consume substantial memory on large text.
Step-by-Step Example
import re
log_text = 'ID: 12; ID: 34'
print(re.findall(r'ID: (\d+)', log_text))
print(re.findall(r'(ID): (\d+)', log_text))
Understanding the Example
- The expression "'ID: 12; ID: 34'" supplies the value stored as 'log_text'. 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:
['12', '34']
[('ID', '12'), ('ID', '34')]
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
Use finditer() to process match objects lazily with their positions.
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
- Expecting findall() to return Match objects or forgetting that capture groups alter its return structure.
- Extract all four-digit numbers from a document.
Key Takeaways
- Collect all nonoverlapping regex matches as a list.
- re.findall(pattern, string) returns strings when there are no capture groups, group strings when one group exists, and tuples when several groups exist.
- Apply the demonstrated operation to the practice input and verify its result before depending on it in a larger program.