Skip to content

Python regex extract substring | Example code

  • by

Using a “re” module findall() function with regex can extract a substring from a given string in Python.

Example extract pattern matches using RegEx in Python

Simple example code, you need to import Python’s re module. Call re.findall(r”pattern (.*)”, string) with pattern as the exact sequence to match within string.

import re

text = "Chennai is a beautiful city.Chennai is the capital of the state of Tamil Nadu"
city = re.findall("Chennai", text)

print(city)

Output:

Python regex extract substring

Another example

Using the search method in this example with bit complex RegEx.

import re

line = '##ParameterValue[part I care about]=garbagegarbage'
m = re.search('\[(.*)\]', line)
print(m.group(1))

Output: part I care about

Do comment if you have any doubts and suggestions on this Python regular expression tutorial.

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