इस ट्यूटोरियल में, हम एक प्रोग्राम लिखने जा रहे हैं जो regexes का उपयोग करके एक स्ट्रिंग में 1(0+1) की सभी घटनाओं को ढूंढता है। . हमारे पास पायथन में एक री मॉड्यूल है जो हमें रेगुलर एक्सप्रेशन के साथ काम करने में मदद करता है।
आइए एक नमूना मामला देखें।
Input: string = "Sample 1(0+)1 string with 1(0+)1 unnecessary patterns 1(0+)1" Output: Total number of pattern maches are 3 ['1(0+)1', '1(0+)1', '1(0+)1']
प्रोग्राम के लिए कोड लिखने के लिए नीचे दिए गए चरणों का पालन करें।
एल्गोरिदम
1. Import the re module. 2. Initialise a string. 3. Create a regex object using regular expression which matches the pattern using the re.compile(). Remember to pass a raw string to the function instead of the usual string. 4. Now, match all the occurrence of the pattern using regex object from the above step and regex_object.findall() method. 5. The above steps return a match object and print the matched patterns using match_object.group() method.
आइए कोड देखें।
उदाहरण
# importing the re module
import re
# initializing the string
string = "Sample 1(0+)1 string with 1(0+)1 unnecessary patterns 1(0+)1"
# creating a regex object for our patter
regex = re.compile(r"\d\(\d\+\)\d") # this regex object will find all the patter ns which are 1(0+)1
# storing all the matches patterns in a variable using regex.findall() method
result = regex.findall(string) # result is a match object
# printing the frequency of patterns
print(f"Total number of pattern maches are {len(result)}")
print()
# printing the matches from the string using result.group() method
print(result) आउटपुट
यदि आप उपरोक्त कोड चलाते हैं, तो आपको निम्न आउटपुट मिलेगा।
Total number of pattern maches are 3 ['1(0+)1', '1(0+)1', '1(0+)1']है
निष्कर्ष
यदि आपको ट्यूटोरियल के बारे में कोई संदेह है, तो उनका टिप्पणी अनुभाग में उल्लेख करें।