regula

Python Regular Expressions

Python Regular Expressions

Regular expressions (regex) are used to search for patterns in text. Python provides the re module for working with regular expressions.

Basic Regex Syntax

Here are some basic regular expression patterns:

Using re Module

You can use the re module to search for patterns in a string. Here's an example of using re.search() to find if a string contains a number:

      
        import re
        pattern = r"\d+"  # Matches one or more digits
        text = "My number is 12345"
        result = re.search(pattern, text)
        if result:
            print("Found a number:", result.group())
        else:
            print("No number found.")
      
    

This code searches for one or more digits in the string and prints the first match found.

Activity

Try It Yourself!

Write a program that uses regular expressions to find all the email addresses in a text.

Quick Quiz

Quick Quiz

  1. What does the \d pattern match?
  2. How do you search for a pattern in a string using Python?

Answers: The \d pattern matches any digit. You can search for a pattern using re.search() or re.findall().