Skip to content

Python substring regex | Example code

  • by

You can create a substring regex pattern to find matches in a given string. You need to capture from regex. Search for the pattern, if found, retrieve the string using group(index).

Python regex Substring match example

Use \b matches start or end of a word. Only one match returns None or a class type object (using .group() returns the exact string matched).

For multiple matches you need re.findall().

import re

str1 = "Good Morning... Hello world!"
str2 = "Hello"

pattern = re.compile(r'\bHello\b')

    match =, str1).group()
except AttributeError:
    print('No match')


Python substring regex


Do comment if you have any doubts and suggestions on this python regular expression topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

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