A couple of years back when I was still a QA engineer (not a Python developer yet) I got myself into dozens of situations where I had to figure out how do I search for a pattern in Python.. A pattern in strings, a pattern in files, etc. Let’s look into possible solutions in this post.

How Do I Search For A Pattern In Python?

To search for a pattern in a string in Python, you can use the re module, which stands for regular expression. Regular expressions are a way to describe patterns in strings, and the re module provides several functions to work with them in Python.

Suppose you have a list of emails, and you want to extract the username and domain name from each email address.

The emails look like this:

jane.doe@example.com
john.smith@gmail.com

You can use the re module and regular expressions to extract the username and domain name from the email addresses like this:

import re

email = 'jane.doe@example.com'

# Extract the username and domain name using a regular expression
pattern = r'(.+)@(.+)'
match = re.search(pattern, email)

username = match.group(1)
domain = match.group(2)

print(f'Username: {username}')  # Output: 'Username: jane.doe'
print(f'Domain: {domain}')  # Output: 'Domain: example.com'

In this example, we used the re.search() function to find the first occurrence of the pattern in the email address, and then used the group() method to extract the matching substrings.

The regular expression itself uses several special characters to specify the pattern:

  • . matches any single character (except a newline)
  • + matches one or more occurrences of the preceding character
  • ( ) define a capturing group, which allows us to extract the matching substrings using the group() method
Continue reading