Python substring regex | Example code

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.1.3 (Community Edition)

Windows 10

Python 3.7

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


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.