🔍
Advanced Python

Regular Expressions (re module)

Pattern Matching
💡 Regex ek super-powerful "find" hai — normal search sirf exact text dhundta hai, regex PATTERNS dhundta hai (jaise "koi bhi email jaisa dikhne wala text"), bahut flexible aur powerful.

re module regex patterns ke saath text search/match/replace karta hai. Common functions: re.search() (pattern kahi bhi milta hai to match object deta hai), re.match() (sirf string ke shuru mein check karta hai), re.findall() (SAARE matches ek list mein), re.sub() (replace karta hai).

Basic pattern syntax: \d (digit), \w (word character), \s (whitespace), + (ek ya zyada), * (zero ya zyada), ? (optional). [] character class define karta hai, () groups banata hai.

import re

text = "Contact: aarav@example.com or call 9876543210"

# Email dhundo:
email = re.search(r"[\w.]+@[\w.]+", text)
print(email.group())   # "aarav@example.com"

# Sab numbers dhundo:
numbers = re.findall(r"\d+", text)
print(numbers)   # ['9876543210']

# Replace karo:
masked = re.sub(r"\d{10}", "XXXXXXXXXX", text)
print(masked)   # phone number masked ho gaya

# Validation:
is_valid_email = re.match(r"^[\w.]+@[\w.]+\.\w+$", "test@example.com")
print(bool(is_valid_email))   # True
🔍
Regex ek super-powerful "find" hai — normal search sirf exact text dhundta hai, regex PATTERNS dhundta hai (jaise "koi bhi email jaisa dikhne wala text"), bahut flexible aur powerful.
1 / 2
⚡ झट से Recap
  • re.search/match/findall/sub — pattern matching operations
  • \d, \w, \s = digit/word/whitespace; +, *, ? = quantifiers
  • Email/phone validation, text extraction mein bahut common
इस page में (2 subtopics)

Regex groups ((...)) se parts extract kar sakte ho, lekin unhe naam bhi de sakte ho (?P<name>...) se — extracted data ko index (group(1)) ke bajaye naam se access karna zyada readable hai.

import re

text = "Date: 2026-07-28"
match = re.search(r"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})", text)

print(match.group("year"))    # "2026"
print(match.group("month"))   # "07"
print(match.groupdict())       # {'year': '2026', 'month': '07', 'day': '28'}
💡Tip: Named groups especially useful hain jab pattern complex ho aur multiple groups extract karne hon — group(1), group(2) yaad rakhne se group("year") zyada maintainable hai.

Agar same pattern baar-baar use karna hai (jaise loop ke andar), re.compile() se pehle compile kar lo — ye pattern ko ek reusable object bana deta hai, repeated matching thoda fast hoti hai.

import re

pattern = re.compile(r"\d+")   # ek baar compile karo

for text in ["abc 123", "def 456", "ghi 789"]:
    match = pattern.search(text)   # reuse — recompile nahi hota har baar
    print(match.group())
💡Tip: Chhote/one-off use cases ke liye re.search(pattern, text) directly likhna kaafi hai — re.compile() sirf tab meaningful farq deta hai jab same pattern hazaaron baar use ho rahi ho (jaise bade loops mein).