Python 3D Academyবাংলা

Regular expressions: patterns that find text

🌍 In real life. Your bank sends a text: "Paid Tk 450 at the shop. Balance Tk 12300." You want every amount in it. Searching for "450" finds just that one number. What you really want is "any run of digits", whatever the digits are.

A regular expression (regex, for short) describes the shape of the text you want, not the exact text. Step by step:

  1. import re, Python's regex module
  2. write the pattern as a raw string, r"...", so every backslash reaches re untouched
  3. a few codes stand for kinds of character: \d a digit, \w a letter, digit or _, \s a space, . any character
  4. square brackets mean "one of these": [aeiou] is a vowel, [0-9] is any digit
  5. re.findall(pattern, text) gives back a list of every match, from left to right

The idea in one sentence: a regular expression is a pattern that describes the text you're looking for, like \d+ for "one or more digits", and re.findall gives back every piece of text that fits it.

Its words:

  • pattern (regex): a description of text, like \d+
  • \d: any digit; +: one or more of the thing before it
  • raw string r"...": keeps backslashes as they are, so r"\d+" reaches re unchanged
  • re.findall (all matches, as a list) and re.search (the first match, or None)
import re

sms = "Paid Tk 450 at the shop. Balance Tk 12300."
print(re.findall(r"\d", sms))
print(re.findall(r"\d+", sms))
print(re.findall(r"[aeiou]", "Dhaka"))
\d finds single digits. Add + ("one or more") and each whole number comes out in one piece. The next lesson is all about repeats like +.

Watch the scanner. The pattern's pieces sit on top, each with what it means. Below is the text, one tile per character, numbered from 0. The glowing lens slides to each place \d+ fits and stretches over the whole number, and each match flies down into the list that findall gives back.

Just the first one: re.search. findall collects everything. re.search stops at the first match and gives back a Match object: m.group() is the text it matched, and m.span() is where (the start, and one past the end). When nothing fits, search gives back None, so check with if m: before using it.

Why the r? In a normal string, Python treats some backslash pairs specially: "\b" becomes an invisible backspace character, not the regex code for a word edge. A raw string r"\b" keeps the backslash, so always write patterns with r.

import re

for text in ["order 7 arrived", "nothing yet"]:
    m = re.search(r"\d+", text)
    if m:
        print("found", m.group(), "at", m.span())
    else:
        print("no number in:", text)

Mistakes and edge cases.

  • Forgetting the r. "\d+" without r makes Python warn SyntaxWarning: "\d" is an invalid escape sequence; always write patterns as raw strings.
  • Using a match that wasn't found. re.search gives None when nothing fits, so m.group() gives AttributeError: 'NoneType' object has no attribute 'group'. Check if m: first.
  • Numbers come back as text. findall gives strings; convert with int().
  • An unclosed bracket in a pattern. re.compile("(ab") gives re.PatternError: missing ), unterminated subpattern at position 0.

Quiz

  1. What does this print?

    import re
    
    print(re.findall(r"\d", "a1b22"))
  2. What does this print?

    import re
    
    print(re.findall(r"\d+", "a1b22"))
  3. What does \w match?

    • One letter, digit or underscore
    • A whole word
    • Any character at all
  4. What does this print?

    import re
    
    m = re.search(r"cat", "a dog and a cat")
    print(m.group(), m.span())
  5. What does this print?

    import re
    
    print(re.search(r"\d", "no digits"))
  6. There's no number in this text, and the program crashes. Which line needs a check before it?

    import re
    m = re.search(r"\d+", "no numbers here")
    print(m.group())

Coding tasks

  1. Write amounts(sms: str) -> list[int]: every whole number in the message, as ints, in order.

  2. Write count_vowels(text: str) -> int with re.findall: how many vowels (a, e, i, o, u, small or capital) the text has.

  3. Write find_email(text: str) -> str | None with re.search: the first email address in the text (letters, digits, _ or ., then @, a name, a dot and an ending, like mina.r@example.com), or None if there is none.