Regex TwFs
This set of TwFs (Tasks with Feedback) are for learning how to to using regular expressions (regexes) in python code.
Go to Linear ViewWhat is a regular expression?
A regular expression (regex) is a sequence of characters that defines a search pattern for matching, finding, or manipulating text.
For example, the regex \d+
applied to “Order 1239 and
45” will match one or more digits. It will return
['1239', '45']
.
id: 1753540127
Why learn how to use regexes (regular expressions)?
Learning regexes takes time because they are abstract and complicated. Therefore, there must be strong reasons to justify why the effort to learn them is worthwhile.
Regexes are powerful tools for working with text. They allow you to:
- Find all text that matches a specific pattern (e.g., all email addresses in a document).
- Replace or modify text that matches a given pattern (e.g., reformatting phone numbers).
- Validate input (e.g., ensuring a password meets certain rules).
Regexes save massive amounts of time. Instead of writing dozens of lines of code to process text, a single regex can often accomplish the task. This makes your code faster to write, easier to maintain, and more efficient.
Regexes are a fundamental coding skill. They are widely used in:
- Programming languages (Python, JavaScript, etc.).
- Command-line tools (grep, sed).
- Text editors (VS Code, Sublime, Vim).
- Data analysis and web scraping.
Regexes are worth the effort. While they take a little time to learn, they pay off by giving you the ability to solve complex text-processing problems quickly and with minimal code.
Wow Factor Examples
Note: AI generated. I have not validated these yet.
Extract all email addresses from a large document:
[\w\.-]+@[\w\.-]+\.\w+
Find all dates in formats like
2025-07-27
or07/27/2025
:\b\d{4}-\d{2}-\d{2}\b|\b\d{2}/\d{2}/\d{4}\b
Validate strong passwords (8+ characters with at least 1 uppercase, 1 lowercase, 1 number):
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d).{8,}$
id: 1753637258
What is a regex?
A regex is short for “regular expression,” and both terms mean the same thing.
A regular expression is a pattern of characters used to search, match, or modify text.
Example: The regex [\w\.-]+@[\w\.-]+\.\w+
will find all
email addresses in a block of text.
id: 1753636232
How do skilled coders use regexes?
Applications involve three steps.
- Define your regex (the search pattern)
- Choose the helper function from the re module that does what you want.
- Write code that does what you want.
Example: Finding all emails in text.
import re
# 1. Define a regex that matches email address.
regex = r"[\w\.-]+@[\w\.-]+\.\w+"
text = "Contact help@chat.com or info@openai.org."
# 2. Select a helper function to find all matches
emails = re.findall(regex, text)
print(emails)
# Results: ['help@chat.com', 'info@openai.org']
id: 1753714203