Regular Expressions (re module)

রেগুলার এক্সপ্রেশন — শক্তিশালী, কিন্তু সতর্কতায় ব্যবহার্য

Read: ~30 min Advanced 5 practice problems Live code runner

1. What Is a Regex?

A regular expression is a tiny pattern language for matching substrings. A few cryptic characters can describe "any 10-digit phone number" or "a valid email". Python's re module gives you matching, searching, replacing, and splitting based on regex.

Regular expression হলো string-এর ভেতর পদার্থ (substring) খুঁজে বের করার জন্য ছোট একটি pattern language। কয়েকটি cryptic অক্ষর দিয়ে "১০-সংখ্যার ফোন নম্বর" বা "সঠিক email" বর্ণনা করা যায়। Python-এর re module match, search, replace ও split করে।

2. Core Functions

FunctionPurpose
re.match(p, s)Match at the start of s.
re.search(p, s)Find first match anywhere.
re.findall(p, s)All non-overlapping matches as a list.
re.finditer(p, s)All matches as an iterator of Match objects.
re.sub(p, r, s)Replace matches with r.
re.split(p, s)Split on pattern.
core.py
import re

s = "Call 017-1234-5678 or 018-9999-0000"

print(re.findall(r"\d{3}-\d{4}-\d{4}", s))

print(re.sub(r"\d", "X", s))

parts = re.split(r"\s+", "python  is     fun")
print(parts)

3. Character Classes & Quantifiers

PatternMatches
.Any char except newline
\d / \DDigit / not digit
\w / \WWord char / not word
\s / \SWhitespace / not
[abc] / [^abc]Any in set / not in set
*0 or more
+1 or more
?0 or 1
{m,n}Between m and n
^ / $Start / end of string

4. Groups — Capturing Parts of a Match

groups.py
import re

log = "[2025-12-16 19:30] INFO  user=ayesha action=login"

m = re.search(r"\[(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2})\] (\w+)", log)
print(m.group(1), "|", m.group(2), "|", m.group(3))

# Named groups — clearer
pat = r"\[(?P<date>\d{4}-\d{2}-\d{2}) (?P<time>\d{2}:\d{2})\] (?P<level>\w+)"
m = re.search(pat, log)
print(m.groupdict())

# Backreference in replacement
print(re.sub(r"(\w+)@(\w+\.\w+)", r"[\1 at \2]",
             "Mail me at rafi@abcltech.com"))

5. Flags & Compiled Patterns

flags.py
import re

# Case-insensitive
print(re.findall(r"python", "Python python PYTHON", re.IGNORECASE))

# Compile once, use many times
email_re = re.compile(r"[\w.+-]+@[\w.-]+\.\w+")
for text in ["contact: a@b.com", "no email here", "x.y@z.co.uk"]:
    print(email_re.findall(text))

# Verbose mode — multi-line with comments
phone_re = re.compile(r"""
    \d{3}      # area code
    [-.\s]?
    \d{4}      # first part
    [-.\s]?
    \d{4}      # second part
""", re.VERBOSE)

print(phone_re.findall("017 1234 5678"))

6. When NOT to Use Regex

Regex is powerful but gets unreadable fast. Avoid it for:

  • Parsing HTML / XML / JSON — use a real parser (html.parser, lxml, json).
  • Truly validating emails — RFC 5322 is far beyond a sensible regex.
  • Nested or recursive structures — regex cannot count matched brackets.
  • Simple string checks — s.startswith(...), s.endswith(...), x in s are clearer.
Rule of thumb: if your regex is longer than two lines or uses more than three special chars in a row, consider parsing manually or with a specialized library.

7. Vocabulary (শব্দভাণ্ডার)

TermMeaningবাংলায়
PatternThe regex expression.Regex নিয়মসূত্র।
Match objectResult object returned by search/match.Search/match-এর ফলাফল object।
GroupA parenthesized capture within a pattern.Pattern-এর ভেতর parenthesize করা capture।
Greedy / LazyMax / min matching behavior.Max / min matching আচরণ।
Raw stringr"...", avoids escaping backslashes.r"..." — backslash escape এড়ানো string।

8. Practice Problems

  1. Extract all numbers from the string "I have 3 mangoes and 15 bananas".
    উপরের string থেকে সব সংখ্যা বের করুন।
    ✨ Show Answer (উত্তর দেখুন)
    ans1.py
    import re
    print(re.findall(r"\d+", "I have 3 mangoes and 15 bananas"))
  2. Replace every 10-digit phone number in a text with XXX-XXX-XXXX.
    Text-এর প্রতিটি ১০-সংখ্যার ফোন নম্বরকে XXX-XXX-XXXX-এ replace করুন।
    ✨ Show Answer (উত্তর দেখুন)
    ans2.py
    import re
    text = "Call 0171234567 or 0189876543"
    print(re.sub(r"\d{10}", "XXX-XXX-XXXX", text))
  3. Parse "2025-12-16" into year, month, day using named groups.
    Named group দিয়ে তারিখকে year/month/day-এ ভাগ করুন।
    ✨ Show Answer (উত্তর দেখুন)
    ans3.py
    import re
    m = re.match(r"(?P<y>\d{4})-(?P<m>\d{2})-(?P<d>\d{2})", "2025-12-16")
    print(m.groupdict())
  4. Validate whether a string is a simple email (letters/digits @ letters/digits . letters).
    একটি string সাধারণ email কি না তা চেক করুন।
    ✨ Show Answer (উত্তর দেখুন)
    ans4.py
    import re
    pattern = re.compile(r"^[\w.+-]+@[\w.-]+\.\w+$")
    for s in ["rafi@abcltech.com", "not an email", "a.b@c.co.uk"]:
        print(s, bool(pattern.match(s)))
  5. Find all words starting with a vowel in a sentence.
    একটি বাক্যে vowel দিয়ে শুরু হওয়া সব শব্দ খুঁজে বের করুন।
    ✨ Show Answer (উত্তর দেখুন)
    ans5.py
    import re
    s = "Anyone can learn Python if they try every day"
    print(re.findall(r"\b[aeiouAEIOU]\w*", s))

Summary — Module 27

Regex is the right tool for pattern-based extraction, validation, and replacement. Learn findall, search, sub, and the core metacharacters. Use raw strings (r"...") and named groups for readability, and compile frequently used patterns. When a regex feels like a puzzle — stop, and use a real parser.

Regex pattern-ভিত্তিক extraction, validation, replacement-এর সঠিক tool। findall, search, sub ও মূল metacharacter শিখে নিন। Raw string এবং named group ব্যবহার করুন; বারবার ব্যবহৃত pattern compile করুন। Regex যদি ধাঁধার মতো মনে হয় — থামুন, সঠিক parser ব্যবহার করুন।

Next Module → Type Hints & Static Typing (mypy)।