Level 1
0 / 100 XP

Regex 101

Welcome to the "Regex 101" lesson! In this lesson, we'll dive into the fundamentals of regular expressions (Regex) and explore their syntax and usage in Python. Regex patterns are powerful tools for pattern matching and string manipulation, allowing you to search, validate, and extract specific patterns from text data. Let's get started!

First I want to make you aware of an invaluable tool when it comes to learning and visualizing Regex patterns. My favorite regex website, regex101.com. When you open the website, make sure you set the flavor to Python before using it to understand how these patterns work. I regularly use this tool to build and test regex patterns quickly, and I think you will find it useful too!

Now that you know that, lets begin by understanding the basic syntax of Regex. A Regex pattern is composed of characters and metacharacters that define a specific pattern to match in a string. Let's consider a simple example where we want to match the word "apple" in a text. We can construct a Regex pattern using the re module in Python as follows:

Python
import re text = "I love apples!" pattern = r"apple" matches = re.findall(pattern, text) print(matches)

Let's break down what is happening in the code above.

  • import the re module,
  • define a sample text that contains the word "apple,"
  • construct a Regex pattern r"apple".

The r before the pattern string denotes a raw string, which is commonly used with Regex patterns to avoid potential issues with escape characters.

  • re.findall() function to find all occurrences of the pattern in the given text.

The function returns a list of matches. In this case, it will print ['apple'] , indicating that the pattern was found once in the text.

Try running the code above in your the Python editor, then try changing it to extract the word "love" from the text variable.

Now, let'…