Regular Expressions (re module)
রেগুলার এক্সপ্রেশন — শক্তিশালী, কিন্তু সতর্কতায় ব্যবহার্য
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.
re module match, search, replace ও split করে।
2. Core Functions
| Function | Purpose |
|---|---|
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. |
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
| Pattern | Matches |
|---|---|
. | Any char except newline |
\d / \D | Digit / not digit |
\w / \W | Word char / not word |
\s / \S | Whitespace / 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
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
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 sare clearer.
7. Vocabulary (শব্দভাণ্ডার)
| Term | Meaning | বাংলায় |
|---|---|---|
| Pattern | The regex expression. | Regex নিয়মসূত্র। |
| Match object | Result object returned by search/match. | Search/match-এর ফলাফল object। |
| Group | A parenthesized capture within a pattern. | Pattern-এর ভেতর parenthesize করা capture। |
| Greedy / Lazy | Max / min matching behavior. | Max / min matching আচরণ। |
| Raw string | r"...", avoids escaping backslashes. | r"..." — backslash escape এড়ানো string। |
8. Practice Problems
-
Extract all numbers from the string
"I have 3 mangoes and 15 bananas".উপরের string থেকে সব সংখ্যা বের করুন।✨ Show Answer (উত্তর দেখুন)
ans1.pyimport re print(re.findall(r"\d+", "I have 3 mangoes and 15 bananas")) -
Replace every 10-digit phone number in a text with
XXX-XXX-XXXX.Text-এর প্রতিটি ১০-সংখ্যার ফোন নম্বরকেXXX-XXX-XXXX-এ replace করুন।✨ Show Answer (উত্তর দেখুন)
ans2.pyimport re text = "Call 0171234567 or 0189876543" print(re.sub(r"\d{10}", "XXX-XXX-XXXX", text)) -
Parse
"2025-12-16"into year, month, day using named groups.Named group দিয়ে তারিখকে year/month/day-এ ভাগ করুন।✨ Show Answer (উত্তর দেখুন)
ans3.pyimport re m = re.match(r"(?P<y>\d{4})-(?P<m>\d{2})-(?P<d>\d{2})", "2025-12-16") print(m.groupdict()) -
Validate whether a string is a simple email (letters/digits @ letters/digits . letters).একটি string সাধারণ email কি না তা চেক করুন।
✨ Show Answer (উত্তর দেখুন)
ans4.pyimport 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))) -
Find all words starting with a vowel in a sentence.একটি বাক্যে vowel দিয়ে শুরু হওয়া সব শব্দ খুঁজে বের করুন।
✨ Show Answer (উত্তর দেখুন)
ans5.pyimport 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.
findall, search, sub ও মূল metacharacter শিখে নিন। Raw string এবং named group ব্যবহার করুন; বারবার ব্যবহৃত pattern compile করুন। Regex যদি ধাঁধার মতো মনে হয় — থামুন, সঠিক parser ব্যবহার করুন।