HTML

    Select a Subtopic

    Day 10: Regular Expressions

    Learn the fundamentals of Regular Expressions in Python and master pattern matching!

    Topics:

    • Introduction to `re` module
    • Pattern Matching
    • Common Regex Methods
    • Special Characters in Regex

    1. Introduction to re module

    The re module in Python provides support for regular expressions, enabling you to perform pattern matching and string manipulation.

    To use it, import the module like this:

    import re

    2. Pattern Matching

    Regular expressions allow you to define patterns for matching specific sequences in text. Here are some common patterns:

    • \\d - Matches any digit (0-9)
    • \\w - Matches any alphanumeric character (letters and digits)
    • \\s - Matches any whitespace character (spaces, tabs, line breaks)

    3. Common Regex Methods

    The re module includes several methods for pattern matching:

    # Using re.match() to match a pattern at the beginning of the string result = re.match(r'\d+', '123abc') print(result.group()) # Output: 123
    # Using re.search() to find the first match result = re.search(r'\d+', 'abc123xyz') print(result.group()) # Output: 123

    4. Special Characters

    Special characters in regular expressions have unique meanings:

    • . - Matches any character except newline
    • ^ - Matches the beginning of the string
    • $ - Matches the end of the string
    • * - Matches 0 or more repetitions of the preceding character or group

    Exercises:

    • Validate an email address using regex: Create a function to validate if an email follows the basic structure username@domain.com
    • Extract phone numbers: Use regex to extract phone numbers from a text file or string (example format: (123) 456-7890)

    Summary

    On Day 10, we explored the power of **Regular Expressions** in Python. We learned how to use the re module for pattern matching, and we covered the common methods for searching, matching, and replacing text. You also learned some key special characters in regex and applied this knowledge in exercises.