Skip to content

Python string contains regex

  • by

To check if a Python string contains a regular expression pattern, you can use the re module, which provides functions for working with regular expressions.

Regular expressions (regex or regexp) are powerful tools for pattern matching and searching within strings.

Python string contains regex example

Simple example code.

import re

# The string you want to search
input_string = "Hello, my email is [email protected] and my phone number is 123-456-7890."

# The regular expression pattern you want to search for
pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,7}\b'  # Example pattern for email addresses

# Use re.search() to find a match
if re.search(pattern, input_string):
    print("String contains the pattern")
else:
    print("String does not contain the pattern")

In the above example, we’re searching for an email address pattern within the input string. The re.search() function returns a match object if it finds a match, and None if there’s no match. You can adjust the pattern variable to match the specific regular expression you’re interested in.

import re

# The string you want to search
input_string = "My phone number is 123-456-7890."

# The regular expression pattern you want to search for
pattern = r'\d{3}-\d{3}-\d{4}'  # Example pattern for a phone number

# Use re.search() to find a match
match = re.search(pattern, input_string)

if match:
    print("String contains the pattern:", match.group())
else:
    print("String does not contain the pattern")

Output:

Python string contains regex

In this example, we’re searching for a phone number pattern (e.g., “123-456-7890”) within the input string. If a match is found, re.search() returns a match object, and you can use .group() to extract the matched text. If there’s no match, it returns None.

Make sure to adjust the pattern variable to match the specific regular expression you’re interested in.

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