How to Search Text in Python using Regular Expressions


In this article, we show how to search text in Python using regular expressions.

We will use the function in order to search a text for a particular character or subexpression.

We will show how to obtain the result, how to obtain the index of the start of the result found, and the index of the end of the result found.

Thus, we can find the match, as well as the index locations it spans across.

So we're just going to use a very simple example in this article.

We're going to write a regular expression that looks for a 4-digit number in a string.

This 4-digit number represents the year the person was born.

We want to use a regular expression to extract this year from the string.

We then will print what index locations it spans across, including the start index and the end index.

This is shown in the code below.

So let's now go over this code.

re is the module in Python that allows us to use regular expressions. So we first have to import re in our code, in order to use regular expressions.

After this, we have a variable, phrase, which contains the string that we want to search using regular expressions.

We then create the variable, Match, and set it equal to,"\d{4}", phrase)

This looks for a 4-digit number within the variable, phrase.

To print the match found, you can do so using,

To print the index locations the match spans in the string, you can do so using, match.span()

To print the start index location of the match in the string, you can do so using, match.start()

To print the end index location of the match in the string, you can do so using, match.end()

And this is how we can search a string for a singular instance of a match within the string and find the index locations of the match within the string.

Related Resources

How to Randomly Select From or Shuffle a List in Python

HTML Comment Box is loading comments...