How to Check if String Matches Pattern in Python
In Python, use the
re module's match() or search() functions to check if a string matches a pattern. The match() function checks from the start of the string, while search() looks anywhere in the string.Syntax
Use the re module functions to check patterns in strings:
re.match(pattern, string): Checks if the string starts with the pattern.re.search(pattern, string): Checks if the pattern appears anywhere in the string.patternis a regular expression describing the pattern.- Returns a match object if found, otherwise
None.
python
import re match_obj = re.match(r'pattern', 'string to check') search_obj = re.search(r'pattern', 'string to check')
Example
This example shows how to check if a string starts with 'Hello' and if it contains 'world' anywhere.
python
import re text = 'Hello, world!' # Check if string starts with 'Hello' if re.match(r'Hello', text): print('String starts with Hello') else: print('String does not start with Hello') # Check if string contains 'world' anywhere if re.search(r'world', text): print('String contains world') else: print('String does not contain world')
Output
String starts with Hello
String contains world
Common Pitfalls
Common mistakes when checking string patterns include:
- Using
re.match()when you want to find a pattern anywhere in the string (usere.search()instead). - Not using raw strings (
r'') for patterns, which can cause errors with backslashes. - Assuming
re.match()returnsTrueorFalseinstead of a match object orNone.
python
import re text = 'Say hello to the world' # Wrong: re.match looks only at start if re.match(r'world', text): print('Found world at start') else: print('Did not find world at start') # Right: use re.search to find anywhere if re.search(r'world', text): print('Found world anywhere') else: print('Did not find world anywhere')
Output
Did not find world at start
Found world anywhere
Quick Reference
| Function | Description | Returns |
|---|---|---|
| re.match(pattern, string) | Checks if string starts with pattern | Match object or None |
| re.search(pattern, string) | Checks if pattern appears anywhere in string | Match object or None |
| match_obj.group() | Gets matched text from match object | Matched substring |
| re.fullmatch(pattern, string) | Checks if entire string matches pattern | Match object or None |
Key Takeaways
Use re.match() to check if a string starts with a pattern.
Use re.search() to find a pattern anywhere in the string.
Always use raw strings (r'') for regex patterns to avoid errors.
re.match() and re.search() return match objects, not booleans.
Use re.fullmatch() to check if the whole string matches the pattern.