Python re.search() method is “used to search for occurrences of the regex pattern inside the entire target string and returns the corresponding Match Object instance where the match found.”
The re.search() method takes two required parameters.
- pattern: It is the pattern that we have to check against the string.
- string: It is a string in which we find the pattern.
The search() function returns a Match object if there is a match.
Example 1: How to Use re.search() Method
import re txt = "Millie Finn Gaten" sub_str = re.search("\s", txt) print("The first white-space character is located in position:", sub_str.start())
The first white-space character is located in position: 6
Example 2: If no matches are found
If no matches are found, the value None is returned.
import re txt = "Millie Finn Gaten" sub_str = re.search("\n", txt) print("The first white-space character is located in position:", sub_str)
The first white-space character is located in position: None
Python re.search() vs re.match()
There is a difference between Python re.search() and re.match() functions.
Both functions return the first match of a substring found in the string, but the re.match() method searches only in the first line of the string and returns a match object if found, else returns none.
But if a match of substring is found in some other line other than the first line of string (in case of a multi-line string), it returns None.
While the re.search() method searches for the whole string even if the string contains multi-lines and tries to find a match of the substring in all the lines of the string.
import re Substring = 'lived' String = '''The boy who lived come to die''' # Use of re.search() Method print(re.search(Substring, String, re.IGNORECASE)) # Use of re.match() Method print(re.match(Substring, String, re.IGNORECASE))
<re.Match object; span=(12, 17), match='lived'> None
The re.search() method returns a match object and implies that the first match is found at index 17.
The re.match() method returns None because the match exists in the second line of the string, and re.match() searches only in the first line.
The re.IGNORECASE is used to ignore the case sensitivity in the strings.
The re.search() and re.match() method returns only the first occurrence of a substring in the string and ignores others.