← Go Back

How to Make a Text Search Using Regular Expressions

Python has standard support for regular expressions in the re module. For example, here's how to search for a name within a string:

import re

text = "Hello, world!"
# Find all characters between ", " and "!".
match = re.search(r", (?P<name>(.*))!", text)
if match is not None:
name = match.group("name")
print("Found name:", name)
else:
print("Name not found")

Output:

Found name: world

And here's how to get everything that matches certain pattern:

import re

text = """
Hello, World!
Hello, John!
Hello, Sophia!
Hello, Emma!
"""
names = re.findall(r", (.*)!", text)
if names:
print("Names found:")
for name in names:
print(name)
else:
print("No name found.")

Output:

Names found:
World
John
Sophia
Emma


For an explanation of regular expressions syntax, see the official documentation.

regular-expressions strings


🐍 You might also find interesting: