
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Significance of regex.match() and regex.search() Function in Python
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
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
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
Advertisements