Python regex re.search() method looks 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() returns only the first match to the pattern from the target string. Use a re.search() to search pattern anywhere in the string.
Table of contents
How to use re.search()
Before moving further, let’s see the syntax of it.
Syntax
re.search(pattern, string, flags=0)Code language: Python (python)
The regular expression pattern and target string are the mandatory arguments, and flags are optional.
pattern: The first argument is the regular expression pattern we want to search inside the target string.string: The second argument is the variable pointing to the target string (In which we want to look for occurrences of the pattern).flags: Finally, the third argument is optional and it refers to regex flags by default no flags are applied.
There are many flags values we can use. For example, the re.I is used for performing case-insensitive searching. We can also combine multiple flags using bitwise OR (the | operator).
Return value
The re.search() method returns a Match object ( i.e., re.Match). This match object contains the following two items.
- The tuple object contains the start and end index of a successful match.
- Second, it contains an actual matching value that we can retrieve using a
group()method.
If the re.search() method fails to locate the occurrences of the pattern that we want to find or such a pattern doesn’t exist in a target string it will return a None type.
Now, Let’s see how to use re.search().