The re.match() method in Python is used to check whether a regular expression pattern matches the beginning of a string. It returns a match object when the pattern matches at the start of the string; otherwise, it returns None.
import re
s = "Hello, World!"
match = re.match("Hello", s)
if match:
print("Pattern found!")
else:
print("Pattern not found.")
Output
Pattern found!
Syntax
re.match(pattern, string, flags=0)
Parameters:
- pattern: Regular expression pattern to be matched.
- string: String in which the pattern is checked.
- flags: Optional flags that modify the matching behavior, such as re.IGNORECASE.
Return Value:
- Returns a match object if the pattern matches at the beginning of the string.
- Returns None if no match is found.
Using re.match with Regular Expressions
Regular expressions can be used with re.match() to check more complex patterns, such as whether a string starts with a number.
import re
s = "123abc"
match = re.match(r"\d", s)
if match:
print("Starts with a number.")
else:
print("Doesn't start with a number.")
Output
Starts with a number.
Explanation:
- r"\d" represents a digit pattern.
- re.match() checks the pattern at the beginning of s.
- Since "123abc" starts with a digit, a match is found.
Accessing Match Object
When re.match() finds a match, it returns a match object. Methods such as group() can be used to access the matched text.
import re
s = "Python is great"
match = re.match(r"Python", s)
if match:
print(f"Match found: {match.group()}")
else:
print("No match.")
Output
Match found: Python
Explanation:
- re.match() checks whether "Python" occurs at the beginning of the string.
- match stores the returned match object.
- group() returns the matched text.
- If no match is found, match contains None.
Using flags
The flags parameter can modify how the pattern is matched. For example, re.IGNORECASE makes the matching case-insensitive.
import re
s = "Python is great"
match = re.match("python", s, re.IGNORECASE)
if match:
print("Match found")
else:
print("No match")
Output
Match found
Explanation:
- "python" is matched against the beginning of the string.
- re.IGNORECASE ignores differences between uppercase and lowercase letters.
- Therefore, "python" matches "Python".
Note: re.match() checks only the beginning of the string. To search for a pattern anywhere in the string, use re.search().