Significance of regex match() and regex search() function in Python

PythonServer Side ProgrammingProgramming

There are two types of operations that can be performed using regex, (a) search and (b) match. In order to use regex efficiently while finding the pattern and matching with the pattern, we can use these two functions.

Let us consider that we have a string. regex match() checks the pattern only at the beginning of the string, while regex search() checks the pattern anywhere in the string. The match() function returns the match object if a pattern is found, otherwise none.

  • match() – Finds the pattern only at the beginning of the string and returns the matched object.
  • search() – Checks for the pattern anywhere in the string and returns the matched object.

In this example, we have a string and we need to find the word 'engineer' in this string.

Example

Live Demo

import re
pattern = "Engineers"
string = "Scientists dream about doing great things. Engineers Do them"
result = re.match(pattern, string)
if result:
   print("Found")
else:
   print("Not Found")

Running this code will print the output as,

Output

Not Found

Now, let us use the above example for searching,

Example

Live Demo

import re
pattern = "Engineers"
string = "Scientists dream about doing great things. Engineers Do them"
result = re.search(pattern, string)
if result:
   print("Found")
else:
   print("Not Found")

Running the above code will print the output as,

Output

Found
raja
Published on 23-Feb-2021 05:38:54
Advertisements