🟡 Advanced Python  ·  Lesson 23

re Module के साथ Regular Expressions

Regular Expression क्या है?

Regular expression (regex) एक pattern है जो text को search, match या extract करने के लिए use होता है। Python का re module इसे चलाता है। Regex emails, phone numbers, PIN codes आदि check करने के लिए बढ़िया है।

Common Patterns

PatternMatches
\dकोई digit (0-9)
\wletter, digit या underscore
\sएक space
.कोई भी character
+एक या ज़्यादा
*शून्य या ज़्यादा
{n}ठीक n बार

re Functions

  • re.search() — कहीं भी पहला match ढूंढे।
  • re.findall() — सभी matches list में लौटाए।
  • re.match() — सिर्फ शुरुआत में match।
  • re.sub() — matches replace करे।

Program 1: Pattern ढूंढें

Python – find.py
import re
text = "My roll number is 42"
match = re.search(r"\d+", text)
if match:
    print("Found number:", match.group())
Found number: 42

r"\d+" मतलब "एक या ज़्यादा digits"। .group() matched text लौटाता है।

Program 2: Email Validate करें

Python – email.py
import re
pattern = r"^[\w.]+@[\w]+\.[a-z]{2,}$"
email = input("Enter email: ")
if re.match(pattern, email):
    print("Valid email")
else:
    print("Invalid email")
Enter email: aman@gmail.com Valid email
  • [\w.]+ = name part; @ literal; [\w]+ = domain।
  • \.[a-z]{2,} = एक dot फिर कम से कम 2 letters (com, in...)।

Program 3: सभी Phone Numbers निकालें

Python – phones.py
import re
text = "Call 9876543210 or 9123456780 today"
numbers = re.findall(r"\d{10}", text)
print("Phone numbers:", numbers)
Phone numbers: ['9876543210', '9123456780']

\d{10} ठीक 10 digits match करता है; findall हर match list में लौटाता है।

सामान्य गलतियाँ

  • r"..." raw string भूलना — backslashes गलत पढ़े जाते हैं।
  • search (कहीं भी) की जगह match (सिर्फ शुरू) use करना।
  • Patterns को बहुत जटिल बनाना — simple से शुरू करके test करें।

Practice Tasks

  1. Check करें कि string में कोई digit है या नहीं।
  2. 6-digit PIN code validate करें।
  3. बड़े अक्षर से शुरू होने वाले सभी words निकालें।
  4. re.sub से string के सभी spaces को hyphens से replace करें।

सारांश

  • Regex re module से text patterns match करता है।
  • मुख्य patterns: \d digit, \w word char, + एक-या-ज़्यादा, {n} ठीक n।
  • Functions: search, findall, match, sub। हमेशा raw strings r"..." use करें।
← Back to Python Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 लाइव कोड एडिटर

इस पेज के प्रोग्राम यहीं तैयार हैं — चलाएँ, बदलें और सीखें। कुछ भी इंस्टॉल किए बिना।
OneCompiler द्वारा संचालित। कोड एडिटर में अपने आप आ जाता है — Run दबाकर आउटपुट देखें। अगर एडिटर न खुले तो नए टैब में खोलें.