Pattern Matching का मतलब होता है किसी दिए गए text (string) में एक विशेष pattern को match करना। यह तब उपयोगी होता है जब हमें string के अंदर किसी विशेष format, structure, या sequence को खोजने की जरूरत होती है।
Python में pattern matching के लिए regular expressions (regex) का उपयोग किया जाता है। Regular expressions एक शक्तिशाली tool है, जो string में complex patterns को match करने के लिए काम आता है।
Python में Regex का उपयोग कैसे करें?
Python में regex का उपयोग करने के लिए re module का उपयोग किया जाता है। re module में बहुत सारें functions होते हैं, जो हमें patterns को match करने, search करने, replace करने और split करने की सुविधा प्रदान करते हैं।
Python में regex का उपयोग करने के लिए, सबसे पहले re module को import करना होता है:-
import re
महत्वपूर्ण Regex Functions
Regex के कुछ मुख्य functions निम्नलिखित हैं:-
1:- re.match()
यह फंक्शन string के शुरुआत से pattern को match करता है। यदि match मिल जाता है, तो यह एक match object को return करता है, अन्यथा None रिटर्न करता है।
import re
result = re.match(r'hello', 'hello world')
if result:
print("Pattern Found")
else:
print("Pattern Not Found")
2:- re.search()
यह function पूरे string में pattern को search करता है। अगर match मिल जाता है तो यह match object को रिटर्न करता है, अन्यथा None रिटर्न करता है।
import re
result = re.search(r'world', 'hello world')
if result:
print("Pattern Found")
else:
print("Pattern Not Found")
3:- re.findall()
यह फंक्शन string में match होने वाले सभी patterns को list के रूप में रिटर्न करता है।
import re
result = re.findall(r'\d+', 'hello 123 world 456')
print(result) # Output: ['123', '456']
4:- re.sub()
यह फंक्शन string में match होने वाले pattern को replace करता है।
import re
result = re.sub(r'hello', 'hi', 'hello world')
print(result) # Output: hi world
5:- re.split()
यह फंक्शन string को split करने के लिए pattern का उपयोग करता है।
import re
result = re.split(r'\s+', 'Kaise Hai Aap')
print(result) # Output: ['Kaise', 'Hai', 'Aap']
Example: Pattern Matching using re
मान लीजिए, हमें एक email address को match करना है। हम regex pattern का उपयोग करके इसे match कर सकते हैं:-
import re
email = "[email protected]"
pattern = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
if re.match(pattern, email):
print("Valid Email")
else:
print("Invalid Email")
इसे पढ़ें:-