Computer >> Computer tutorials >  >> Programming >> Python

What is the match() function in Python?


In Python, match() is a method of the module re 

Syntax

Syntax of match()

re.match(pattern, string):

This method finds match if it occurs at start of the string. For example, calling match() on the string ‘TP Tutorials Point TP’ and looking for a pattern ‘TP’ will match. However, if we look for only Tutorials, the pattern will not match. Let’s check the code.

Example

import re
result = re.match(r'TP', 'TP Tutorials Point TP')
print result

Output

<_sre.SRE_Match object at 0x0000000005478648>

Above, it shows that pattern match has been found. To print the matching string we use method group. Use “r” at the start of the pattern string, it designates a python raw string.

Example

import re
result = re.match(r'TP', 'TP Tutorials Point TP')
print result.group(0)

Output

TP

Let’s now find ‘Tutorials’ in the given string. Here we see that string is not starting with ‘TP’ so it should return no match. Let’s see what we get −

Example

import re
result = re.match(r'Tutorials', 'TP Tutorials Point TP')
print result

Output

None