What is the difference between Python's re.search and re.match?

PythonServer Side ProgrammingProgramming

Both re.match() and re.search() are methods of the Python module re.

The re.match() 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. 

example

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

Output

TP

The re.search() method is similar to re.match() but it doesn’t limit us to find matches at the beginning of the string only. 

example

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

Output

Tutorials

Here you can see that, search() method is able to find a pattern from any position of the string.

raja
Published on 28-Dec-2017 14:32:57
Advertisements