Python में Regular Expressions
In this page:
import re
re.search(pattern, string)
re.findall(pattern, string)
re.sub(pattern, replacement, string)
re Module
Regular expressions text patterns describe करते हैं जिन्हें आप search, validate, या extract कर सकते हैं, और Python इन्हें एक अलग library के बजाय built-in re module के ज़रिए expose करता है।
जब भी आपको किसी format को जाँचना हो (जैसे email address) या free-form text में से structured टुकड़े निकालने हों, ये standard tool हैं।
उदाहरण: The re Module
import re
match = re.search(r"\d+", "Order 42 shipped") # finds the first run of digits
print(match.group()) # the matched text itself
सभी Matches ढूँढना
re.findall() पूरी string scan करता है और हर non-overlapping match को एक list के रूप में return करता है, जिससे यह तब पहला choice बनता है जब आपको सिर्फ़ पहले वाले के बजाय सभी occurrences में दिलचस्पी हो।
अगर आपके pattern में capturing groups हैं, तो findall() पूरे matches की बजाय group contents के tuples return करता है।
उदाहरण: Finding All Matches
import re
numbers = re.findall(r"\d+", "10 apples, 20 oranges") # returns every match as a list
print(numbers)
Search और Match
re.search() string में कहीं भी देखता है और पहले match पर रुक जाता है, जबकि re.match() तभी सफल होता है जब pattern index 0 से ही शुरू होकर match करे -- एक common bug यह है कि match() इस्तेमाल किया जाए और यह देखकर confuse हुआ जाए कि एक valid pattern सिर्फ़ इसलिए fail हो गया क्योंकि वह बिल्कुल शुरुआत में नहीं था।
उदाहरण: Search and Match
import re
print(re.search(r"World", "Hello World")) # search() finds it anywhere in the string
print(re.match(r"World", "Hello World")) # match() fails since "World" isn't at index 0
Text को Substitute करना
re.sub() किसी pattern का हर match ढूँढता है और उसे एक नई string (या किसी function के result) से replace कर देता है, यही तरीका है जिससे ज़्यादातर text-cleaning pipelines HTML tags strip करती हैं, whitespace normalize करती हैं, या phone numbers जैसी sensitive data को mask करती हैं।
उदाहरण: Substituting Text
import re
text = "Call 123-456-7890"
masked = re.sub(r"\d", "*", text) # replaces every digit with an asterisk
print(masked)
Pattern से Split करना
re.split() किसी string को जहाँ भी pattern match करता है वहाँ तोड़कर एक list बनाता है, जो str.split() से ज़्यादा flexible है क्योंकि delimiter खुद एक pattern हो सकता है -- उदाहरण के लिए एक साथ commas और spaces के किसी भी run पर split करना।
उदाहरण: Splitting by Pattern
import re
parts = re.split(r",\s*", "a, b,c, d") # splits on a comma plus any following spaces
print(parts)
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: