How to find a pattern with re.search in a Python string

Regular expressions are very useful to the Python geek, especially when they have to deal with a lot of data which comes in the form of text. Being very rich in features, the Python computer programming language comes with a builtin module which offers the functionalities and utilities to construct regular expressions based on the coder’s needs.

The name of the Python builtin module which offers the utilities to construct regular expressions, is re. As most of you may understand, its name stands for regular expressions.

First of all, before going any further with this article, make sure to launch a new Python interactive console in your own operating system so you can practice the theory by yourself.

What's the one thing every developer wants? More screens! Enhance your coding experience with an external monitor to increase screen real estate.

Once you have managed to launch a new interactive Python interpreter in your own machine, make sure to import the builtin module needed for constructing regular expressions by making use of the following statement.

import re

Now that you have imported the module which is needed to construct regular expressions, you have to learn how to make use of the re.search function. The syntax for using such function is shown below.

# re.search(pattern, string_obj)
# in the above, the re.search function
# searches for the pattern in string_obj

Let’s run a practical example, with the main purpose of illustrating the usage of the re.search function.

Before we can make use of the re.search function, we need to define a Python string object like shown below.

line_str = 'cats are not like dogs'

Now that we have defined the string object like shown in the above example, we need to define a pattern so we can make use of it to search the string object.

pattern = 'cats'

Now that we have defined both the pattern and the string, we can easily make use of the re.search function like shown below.

re.search(pattern, line_str)

Final thoughts

On success, the re.search function returns a match object, otherwise it returns the Python object None. One can easily check if their function matched anything or not by making use of the following syntax.

obj = re.search(pattern, line_str)
if obj is not None:
    print(obj.group())

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Leave a Reply

Your email address will not be published. Required fields are marked *