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 re.search() 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')

try:
    match = re.search(pattern, str1).group()
    print(match)
except AttributeError:
    print('No match')

Output:

Python substring regex

Source: stackoverflow.com

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading