Python re मॉड्यूल
In this page:
import re
match = re.search(pattern, string)
if match:
match.group()
Patterns खोजना
re मॉड्यूल strings पर regular-expression pattern matching implement करता है।
re.search() पूरी string में pattern कहीं भी match होने की पहली जगह ढूँढता है, और एक match object लौटाता है (या कुछ भी match न होने पर None) -- re.match() से अलग, जो सिर्फ string की बिल्कुल शुरुआत में match चेक करता है।
उदाहरण: Searching for Patterns
import re
match = re.search(r"\d+", "Order 42") # finds the pattern anywhere in the string
print(match.group())
सारे Matches ढूँढना
re.findall() पूरी string स्कैन करता है और हर non-overlapping match को strings की एक list के रूप में लौटाता है, जो बार-बार लूप चलाकर search() को call करने की बजाय एक साथ pattern की हर occurrence निकालने का सबसे आसान तरीका है।
उदाहरण: Finding All Matches
import re
print(re.findall(r"\d+", "10 apples 20 oranges"))
sub() से Strings बदलना
re.sub(pattern, replacement, string) pattern के हर match को ढूँढता है और उसे दिए गए replacement text से बदल देता है, और एक नई string लौटाता है -- Python strings immutable होने के कारण original string जस की तस रहती है।
यह plain substring matching से आगे जाने वाले bulk find-and-replace operations के लिए standard tool है।
उदाहरण: Replacing Strings with sub()
import re
print(re.sub(r"\d", "#", "Call 123"))
Regex Groups इस्तेमाल करना
किसी pattern के हिस्से को parentheses () में लपेटना एक capturing group बनाता है, जिससे आप match के specific sub-pieces निकाल सकते हैं -- जैसे किसी matched email address से सिर्फ domain निकालना -- न कि सिर्फ पूरा matched text वापस पाना।
उदाहरण: Using Regex Groups
import re
match = re.search(r"(\w+)@(\w+)\.com", "[email protected]")
print(match.group(1), match.group(2)) # group(1) and group(2) are the parenthesized captures
Regex Patterns Compile करना
re.compile() किसी pattern string को अपने .search()/.match()/.findall() methods वाले एक reusable regex object में पहले से compile कर देता है।
एक बार compile करके object को दोबारा इस्तेमाल करना Python को हर call पर वही pattern string फिर से parse करने से बचाता है, जो तब मायने रखता है जब आप किसी बड़े loop या dataset पर एक ही pattern लागू कर रहे हों।
उदाहरण: Compiling Regex Patterns
import re
pattern = re.compile(r"\d+") # compiled once, reusable across many calls
print(pattern.findall("10 apples 20 oranges"))
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: