Python re.search() – Search in String using Regular Expression

Python re.search() Function

re.search() function returns the first match for a pattern in a string. The search happens from left to right.

In this tutorial, we will learn how to use re.search() function with the help of example programs.

Syntax – re.search()

The syntax of re.search() function is

re.search(pattern, string, flags=0)

where

ParameterDescription
pattern[Mandatory] The pattern which has to be found in the string.
string[Mandatory] The string in which the pattern has to be found.
flags[Optional] Optional flags like re.IGNORECASE, etc.

Return Value

The function returns a re.Match object.

Example 1: re.search()

In this example, we will take a pattern and a string. The pattern represents a continuous sequence of lowercase alphabets. We will find the first match of this pattern in the string using re.search() function and print it to console.

Python Program

import re

pattern = '[a-z]+'
string = '-----2344-Hello--World!'
result = re.search(pattern, string)
print(result)
Run Code Copy

Output

<re.Match object; span=(11, 15), match='ello'>

re.search() returns a re.Match object. To get the matching text as string, use group() function on the re.Match object as shown in the following program.

Python Program

import re

pattern = '[a-z]+'
string = '-----2344-Hello--World!'
result = re.search(pattern, string)
print(result.group())
Run Code Copy

Output

ello

And coming to the output, we are looking for a pattern of continuous lower case alphabets, which in case of given string, is ello.

Example 2: re.search() – Pattern Not in String

In this example, we will take a pattern and a string such that the pattern is not present in the string. Now, when you call re.search() where given pattern does not find a match in the string, the function returns None.

Python Program

import re

pattern = '[a-z]+'
string = '-----2344-HELLO--WORLD!'
result = re.search(pattern, string)
print(result)
Run Code Copy

Output

None

Summary

In this tutorial of Python Examples, we learned how to use re.search() function to get the first matching for a given pattern in a string, with the help of example programs.

Code copied to clipboard successfully 👍