Regular Expressions

Learn about regular expressions and their functionality in Python.

The string methods find(), index(), and the membership operator in let us find out whether a string is a substring of another. However, we often need a more sophisticated pattern-matching ability. This is facilitated through regular expressions (also called REs or regex).

Regular expressions are often used for validating input. For example, when we fill out a form online, the name, age, email address, mobile number, etc., are matched against acceptable patterns. The input is considered valid if the values we enter match these patterns.

For example, a mobile number is considered invalid if its length is not 10 characters and it contains anything other than digits.

Regex functionality

The module re contains many useful functions and methods that help us create and use regular expressions.

The most commonly used function of the re module is search(), as shown below:

Get hands-on with 1200+ tech skills courses.