Skip to main content
How To Use Regex With Python

How To Use Regex With Python

This Python tutorial will help you understand Regular expressions (RegEx) using Python 3. We will work with RegEx using Python’s re module. In the UNIX world, regular expressions are widely used.

Python Regex

A Regular Expression (RegEx) is a special sequence of characters that defines a search pattern. This helps you match or find other strings or sets of strings.

Python re Module

To work with Regular Expressions, Python has a built-in package called re. Regular expressions are fully supported in Python thanks to the Python module re. If an error occurs while compiling or using a regular expression, the re module handles it with re.error.

Checkout other python String tutorials:

Python regex Search Example

Using a Python regular expression, we will determine whether a substring exists or not in the string. The following code examples will assist you in determining whether a string contains the specified search pattern.

import re
sub_str_reg = 'python[^\d+$]'
source_str =  "Hello, I am pythonpip blog admin"
regexp = re.compile(sub_str_reg)
if regexp.search(source_str):
  print("Substring is found in string '{0}' " .format(source_str))
else: 
  print("Substring is not found in string '{0}' " .format(source_str)) 

in the above code, We imported the re module at the top of the app.py file, then created a regex pattern to search for a substring, and finally compiled the regEx using the re.compile method.

Finally, we check whether the source string contains a substring pattern; if it does, we print a True message; otherwise, we print a False message.

We can also search a substring into a string using ‘in’ operator:

The in Operator

The python has an in-built operator 'in', that can be used to check the Python string contains a substring. It returns a Boolean (either True or False) and can be used as follows:

source_str = "Hello, I am pythonpip blog admin"
substring = "python"

if substring in source_str:
    print("Substring is found in string '{0}' " .format(source_str))
else:
    print("Substring is not found in string '{0}' " .format(source_str))

You can read more information from official re docs.

Leave a Reply

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