How to Find All Matches in String Python: Simple Guide
To find all matches in a string in Python, use the
re.findall() function from the re module. It returns a list of all non-overlapping matches of a pattern in the string.Syntax
The basic syntax to find all matches in a string is:
re.findall(pattern, string, flags=0)
- pattern: The regular expression pattern you want to search for.
- string: The text where you want to find matches.
- flags: Optional settings to modify matching behavior (like case-insensitive).
python
import re matches = re.findall(r'your_pattern', 'your_string')
Example
This example finds all words that start with 'a' in a sentence.
python
import re text = 'An apple a day keeps the doctor away' pattern = r'\ba\w*' # words starting with 'a' matches = re.findall(pattern, text, flags=re.IGNORECASE) print(matches)
Output
['An', 'apple', 'a', 'away']
Common Pitfalls
One common mistake is using re.search() instead of re.findall(). re.search() returns only the first match, not all matches. Another pitfall is forgetting to use raw strings (prefix r) for regex patterns, which can cause errors with backslashes.
python
import re text = 'cat bat rat' # Wrong: only finds first match first_match = re.search(r'\b\w{3}\b', text) print(first_match.group()) # Output: cat # Right: finds all matches all_matches = re.findall(r'\b\w{3}\b', text) print(all_matches) # Output: ['cat', 'bat', 'rat']
Output
cat
['cat', 'bat', 'rat']
Quick Reference
Remember these tips when finding all matches:
- Use
re.findall()to get all matches as a list. - Use raw strings (prefix
r) for regex patterns. - Use flags like
re.IGNORECASEfor case-insensitive matching. - Check your pattern carefully to match what you want.
Key Takeaways
Use re.findall() to get all matches of a pattern in a string as a list.
Always use raw strings (r'pattern') for regex to avoid errors with backslashes.
re.search() returns only the first match, not all matches.
Use flags like re.IGNORECASE to control matching behavior.
Test your regex pattern to ensure it matches the intended text.