regex का उपयोग करके दो प्रकार के operations perform किए जा सकते हैं: (a) search और (b) match। Pattern ढूंढने और pattern के साथ match करने के लिए regex efficiently उपयोग करने के लिए, हम इन दो functions का उपयोग कर सकते हैं।
मान लीजिए हमारे पास एक string है। regex match() pattern को केवल string की beginning में check करता है, जबकि regex search() pattern को string में कहीं भी check करता है। match() फंक्शन pattern मिलने पर match object return करता है, अन्यथा none।
- match() - Pattern को केवल string की beginning में ढूंढता है और matched object return करता है।
- search() - String में कहीं भी pattern check करता है और matched object return करता है।
इस उदाहरण में, हमारे पास एक string है और हमें इस string में 'engineer' word ढूंढना है।
उदाहरण
import re
pattern = "Engineers"
string = "Scientists dream about doing great things. Engineers Do them"
result = re.match(pattern, string)
if result:
print("Found")
else:
print("Not Found")
यह code चलाने पर output print होगा:
आउटपुट
Not Found
अब, आइए उपरोक्त उदाहरण का उपयोग searching के लिए करें:
उदाहरण
import re
pattern = "Engineers"
string = "Scientists dream about doing great things. Engineers Do them"
result = re.search(pattern, string)
if result:
print("Found")
else:
print("Not Found")
उपरोक्त code चलाने पर output print होगा:
आउटपुट
Found