Python re.match() method



The Python re.match() method is used to determine if the regular expression matches at the beginning of a string. It returns a match object if the pattern is found or 'None' otherwise.

Unlike the method re.search(), the re.match() only checks for a match at the beginning of the string. It is useful for validating input or extracting specific patterns at the start of a string.

This method takes a regular expression pattern and a string as arguments. If the pattern matches the beginning of the string it returns a match object containing information about the match such as the matched text and any captured groups.

Syntax

Following is the syntax and parameters of Python re.match() method −

 re.match(pattern, string, flags=0) 

Parameters

Following are the parameter of the python re.match() method −

  • pattern: The regular expression pattern to search for.
  • string: The input string to search within.
  • flags(optional): These flags modify the behavior of the match. These flags can be combined using bit-wise OR (|).

Return value

This method returns the match object if the pattern is found in the string otherwise it returns None.

Example 1

Following is the basic example of using the re.match() method. In this example the pattern 'hello' is matched against the beginning of the string 'hello, world!' −

 import re result = re.match(r'hello', 'hello, world!') if result: print("Pattern found:", result.group()) else: print("Pattern not found") 

Output

 Pattern found: hello 

Example 2

Here in this example the pattern '\d+-\d+-\d+' is matched against the beginning of the string and groups are used to extract the date components −

 import re result = re.match(r'(\d+)-(\d+)-(\d+)', '2022-01-01: New Year') if result: print("Pattern found:", result.group()) 

Output

 Pattern found: 2022-01-01 

Example 3

Here in this example named groups are used to extract the first and last names from the beginning of the string −

 import re result = re.match(r'(?P<first>\w+) (?P<last>\w+)', 'John Doe') if result: print("First Name:", result.group('first')) print("Last Name:", result.group('last')) 

Output

 First Name: John Last Name: Doe 
python_modules.htm
Advertisements