PY-101 ยท Strings in depth
Regular expressions basics
โฑ 8 min ๐ Real Python 3 ๐ฌ Animated โ Completed
โก The 30-second answer
A regular expression is a pattern that describes text, like \d+ for "one or more digits". Python's re module uses it to search: re.findall(pattern, text) returns every match, re.search finds the first, and re.sub replaces matches. Write patterns as raw strings, r"...", so backslashes stay as typed.
- Read simple patterns (\d, \w, +)
- Find all matches with re.findall
- Replace with re.sub
Try it
Watch it come alive, run it yourself, then prove it. Real Python, right on this page.
Watch Python run the example. Every variable is a jar; watch the values change and the output appear.
import remsg = "Hi, orders ORD-1042 and ORD-77 are late. Call 98765 43210."print(re.findall(r"ORD-\d+", msg))first = re.search(r"\d+", msg)print("First number:", first.group())print(re.sub(r"\d", "#", "PIN 4821"))
Change anything and press Run (or Ctrl+Enter). Then open Watch it and press Watch my code.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Expected output
['ORD-1042', 'ORD-77']
First number: 1042
PIN #### ๐ฏ Use re.findall to print every email address in text as a list. A simple pattern is r"[\w.]+@[\w.]+\.\w+".
Input one line per input() call
Press Run to see the output. Python runs in your browser. Need a hint?
print(re.findall(r"[\w.]+@[\w.]+\.\w+", text))
- The problemA support inbox has 2,000 messages and you need every order number, which looks like ORD- followed by digits. Searching by hand would take a day; a regex takes a line.
- The Python idea
import reA regular expression is a pattern that describes text, like \d+ for "one or more digits". - In real lifeBanks mask account numbers in emails and logs with re.sub so only the last digits are ever visible.
Start with a question
A support inbox has 2,000 messages and you need every order number, which looks like ORD- followed by digits. Searching by hand would take a day; a regex takes a line.
Validating input, extracting IDs from logs and cleaning data all rely on regular expressions.
Explain it like I'm 10
A regex is a "wanted poster" for text: "looks like three digits, a dash, then four digits". Python checks every word against the poster.
The technical explanation
\d is a digit, \w a letter, digit or underscore, \s a space. + means one or more, * zero or more.
re.findall(r"\d+", text) returns a list of every match as strings.
re.sub(r"\d", "#", text) replaces every digit with #.
Syntax
import re
re.findall(r"pattern", text)
re.search(r"pattern", text)
re.sub(r"pattern", replacement, text) Real-world scenario
Banks mask account numbers in emails and logs with re.sub so only the last digits are ever visible.
Test yourself
5 questions. Get 4 right and this lesson is marked complete.
Pass the quiz to complete this lesson.
๐ Every lesson counts toward your certificate Next: Reading and writing files โQuestions people ask
When should I use regex instead of string methods?
Use string methods for fixed text (startswith, split on a comma). Use regex when the text follows a pattern, like "letters, an @, then a domain".
How do I make a regex ignore case in Python?
Pass flags=re.IGNORECASE, for example re.findall(r"python", text, flags=re.IGNORECASE).
Interview questions
How this topic comes up in Python interviews. Answer out loud first, then open the model answer.
beginner When should I use regex instead of string methods?
Use string methods for fixed text (startswith, split on a comma). Use regex when the text follows a pattern, like "letters, an @, then a domain".
beginner How do I make a regex ignore case in Python?
Pass flags=re.IGNORECASE, for example re.findall(r"python", text, flags=re.IGNORECASE).
intermediate What does \d match?
A digit. \d is a digit 0โ9.
intermediate What does + mean in a pattern?
One or more. + repeats one or more times.
Quick revision
Remember
- Read simple patterns (\d, \w, +)
- Find all matches with re.findall
- Replace with re.sub
- Always use raw strings for patterns: r"\d+". Without the r, Python may treat backslashes as its own escape codes.
Syntax
import re
re.findall(r"pattern", text)
re.search(r"pattern", text)
re.sub(r"pattern", replacement, text) Official documentation
- Regular expression HOWTO (docs.python.org)