जब नियमित अभिव्यक्ति का उपयोग करके यह जांचना हो कि कोई दी गई स्ट्रिंग विशिष्ट वर्णों को समाहित करती है या नहीं, तो एक नियमित अभिव्यक्ति पैटर्न परिभाषित किया जाता है, और स्ट्रिंग को इस पैटर्न का पालन करने के अधीन किया जाता है।
उदाहरण
नीचे इसका प्रदर्शन दिया गया है:
import re
def check_string(my_string, regex_pattern):
if re.search(regex_pattern, my_string):
print("The string contains the defined characters only")
else:
print("The string does not contain the defined characters")
regex_pattern = re.compile('^[Python]+$')
my_string_1 = 'Python'
print("The string is :")
print(my_string_1)
check_string(my_string_1, regex_pattern)
my_string_2 = 'PythonInterpreter'
print("\nThe string is :")
print(my_string_2)
check_string(my_string_2, regex_pattern)
आउटपुट
The string is : Python The string contains the defined characters only The string is : PythonInterpreter The string does not contain the defined characters
व्याख्या
आवश्यक पैकेज आयात किए जाते हैं।
'check_string' नामक एक विधि परिभाषित की जाती है, और यह स्ट्रिंग और एक नियमित अभिव्यक्ति को पैरामीटर के रूप में लेती है।
'search' विधि को कॉल किया जाता है और जांचा जाता है कि स्ट्रिंग में वर्णों का एक विशिष्ट समूह मौजूद है या नहीं।
विधि के बाहर, नियमित अभिव्यक्ति पर 'compile' विधि को कॉल किया जाता है।
स्ट्रिंग परिभाषित की जाती है और कंसोल पर प्रदर्शित की जाती है।
इस स्ट्रिंग को पास करके विधि को कॉल किया जाता है।
आउटपुट कंसोल पर प्रदर्शित होता है।