re.match() in Python
Last Updated :
16 Dec, 2024
Improve
re.match method in Python is used to check if a given pattern matches the beginning of a string. It’s like searching for a word or pattern at the start of a sentence. For example, we can use re.match to check if a string starts with a certain word, number, or symbol. We can do pattern matching using re.match in different ways like checking if the string starts with certain characters or more complex patterns.
import re
# Checking if the string starts with "Hello"
s = "Hello, World!"
match = re.match("Hello", s)
if match:
print("Pattern found!")
else:
print("Pattern not found.")
Output
Pattern found!
Syntax of re.match
re.match(pattern, string, flags=0)
Parameters
- pattern: This is the regular expression (regex) that you want to match. It can be any string that defines a pattern, like r"\d" for a digit, or r"[A-Za-z]" for any letter (uppercase or lowercase).
- string: This is the string you want to check for the pattern. re.match will try to match the pattern only at the beginning of the string.
- flags (optional): This is an optional parameter that allows you to modify how the matching should behave. For example, you can use re.IGNORECASE to make the matching case-insensitive. If not provided, the default value is 0.
Returns
- If re.match finds a match at the beginning of the string, it returns a match object.
- If no match is found, it returns None.
Using re.match with Regular Expressions
Regular expressions (regex) allow us to search for more complex patterns. For example, let’s check if a string starts with a number.
import re
# Checking if the string starts with a number
s = "123abc"
# \d means any digit
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.
Accessing Match Object
The result of re.match is a match object if a match is found, or None if no match is found. If a match occurs, we can get more information about it.
import re
s = "Python is great"
match = re.match(r"Python", s)
if match:
print(f"Match found: {match.group()}") # .group() returns the matched string
else:
print("No match.")
Output
Match found: Python