w1coding.comAll tutorials

Python Regula

Python lessons
  1. Environment Setup
  2. Introduction
  3. Control
  4. Control
  5. Loops
  6. Functions
  7. Lists
  8. Dictionary
  9. Classes
  10. Exception
  11. File
  12. Libray
  13. Date
  14. Regula
  15. JSON
  16. Web
  17. Zweb
  18. Apis
  19. Unity
  20. Llampda
  21. Iterators
  22. Generators
  23. Files
  24. Context
  25. Ilogging
  26. Multithreading
  27. Networking
  28. SQLite

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:

  • ^ - Matches the start of the string.
  • $ - Matches the end of the string.
  • .* - Matches any character (except a newline) zero or more times.
  • \d - Matches any digit.
  • \w - Matches any word character (alphanumeric plus underscore).

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().