Python 3D Academyবাংলা

More regex tools, and the traps

🌍 In real life. A shopping list typed by three different people: "tea, cake;samosa ; biscuits". Some used commas, some semicolons, some added spaces. str.split(",") can't handle that mess, but a pattern can describe every kind of separator at once.

Four more tools, step by step:

  1. re.split(pattern, text) splits wherever the pattern matches
  2. re.IGNORECASE lets capital and small letters match each other: give it as the last argument of findall, search or fullmatch, but write flags=re.IGNORECASE for sub and split (their next argument is a count)
  3. re.compile(pattern) makes a pattern object you can use again and again: phone.fullmatch(...), phone.findall(...)
  4. lazy repeats: put ? after a repeat (+?, *?) and it takes as little as it can, instead of as much

The idea in one sentence: re.split cuts text at every separator a pattern describes, flags like re.IGNORECASE change how matching works, ? after a repeat makes it lazy, and re.escape makes ordinary text safe to put in a pattern.

Its words:

  • re.split(r"[,;]\s*", text): split on commas or semicolons, with any spaces after
  • flag: an option such as re.IGNORECASE
  • greedy vs lazy: .+ takes as much as it can; .+? takes as little as it can
  • re.escape(word): put a backslash before every special character
import re

shopping = "tea, cake;samosa ;  biscuits"
print(re.split(r"\s*[,;]\s*", shopping))

print(re.findall(r"tea", "Tea, TEA or tea?", re.IGNORECASE))

phone = re.compile(r"01[3-9]\d{8}")
print(bool(phone.fullmatch("01812345678")), phone.findall("a 01711111111 b 01922222222"))

Capital or small, it's the same tea. With re.IGNORECASE, the pattern tea fits Tea and TEA too:

The greedy trap. You want each HTML tag in "<b>hi</b>". The pattern <.+> grabs <b>hi</b> in one go: .+ is greedy, so it runs to the last > it can find. Make it lazy, <.+?>, and it stops at the first >. Watch the lazy version find two small tags:

Special characters need a backslash. ., +, *, ?, (, ), [, $ and friends mean something in a pattern. To match a real full stop, write \.. The pattern 3.14 also matches 3x14! And when the text to find comes from somewhere else (a user typed it), re.escape(word) adds the backslashes for you.

A pattern with a mistake, like a ( with no ), stops with a PatternError that says where the mistake is.

import re

print(re.findall(r"3.14", "3.14 and 3x14"))
print(re.findall(r"3\.14", "3.14 and 3x14"))
print(re.escape("1+1=2?"))

try:
    re.compile(r"(\d+")
except re.PatternError as e:
    print("pattern mistake:", e)

Why are these traps worth learning? Regex mistakes rarely crash: a greedy pattern or an unescaped dot just matches the wrong text, quietly. Knowing the traps (and testing a pattern on a few tricky examples) is the only defence.

Mistakes and edge cases.

  • Greedy by default. <.+> on "<b>hi</b>" grabs the whole thing; use <.+?>.
  • An unescaped dot. 3.14 also matches 3x14; write 3\.14, or re.escape("3.14").
  • User text as a pattern. A user's "(cake" would break the pattern; escape it first.
  • Splitting with str.split. "a, b;c".split(",") can't handle mixed separators; re.split can.

Quiz

  1. What does this print?

    import re
    
    print(re.split(r"[,;]\s*", "tea, cake;samosa"))
  2. What does this print?

    import re
    
    print(re.findall(r"<.+>", "<b>hi</b>"))
  3. What does this print?

    import re
    
    print(re.findall(r"<.+?>", "<b>hi</b>"))
  4. What does this print?

    import re
    
    print(re.findall(r"tea", "Tea or TEA", re.IGNORECASE))
  5. Which line has a mistake?

    import re
    
    pattern = re.compile(r"(\d+")
    print(pattern.findall("a1 b2"))

Coding tasks

  1. Write split_items(text: str) -> list[str]: split a list on commas and semicolons (with any spaces around them), dropping empty items.

  2. Write strip_tags(html: str) -> str: remove every tag like <b> or </p>, keeping the text between them.

  3. Write count_word(text: str, word: str) -> int: how many times word appears as a whole word, ignoring capitals. "tea" counts in "Tea time" but not in "steam". Use \b and re.escape.