समस्या
आप एक स्ट्रिंग में टेक्स्ट पैटर्न को खोजना और बदलना चाहते हैं।
अगर हमारे पास बहुत सरल लिटरल पैटर्न हैं, तो str.replace() मेथड का उपयोग करना एक इष्टतम समाधान है।
उदाहरण: बेसिक स्ट्रिंग ऑपरेशन्स
def sample():
yield 'Is'
yield 'USA'
yield 'Colder'
yield 'Than'
yield 'Canada?'
text = ' '.join(sample())
print(f"Output \n {text}")
आउटपुट: Is USA Colder Than Canada?
टेक्स्ट खोजने के तरीके:
# सटीक टेक्स्ट खोजें
print(f"Output \n {text == 'USA'}")
आउटपुट: False
# बेसिक स्ट्रिंग मेथड्स का उपयोग करें
print(f"Output \n {text.startswith('Is')}") # True
print(f"Output \n {text.endswith('Canada?')}") # True
print(f"Output \n {text.find('USA')}") # 3 (इंडेक्स)
जटिल पैटर्न के लिए रेगुलर एक्सप्रेशन्स (re मॉड्यूल)
import re
# डेट स्ट्रिंग फॉर्मेट में बनाएं
date1 = '22/10/2020'
# जांचें कि टेक्स्ट में एक से अधिक डिजिट हैं
# \d+ - एक या अधिक डिजिट से मिलान
if re.match(r'\d+/\d+/\d+', date1):
print('yes')
else:
print('no')
आउटपुट: yes
टेक्स्ट बदलना
सरल रिप्लेसमेंट के लिए str.replace()
print(f"Output \n {text.replace('USA', 'Australia')}")
आउटपुट: Is Australia Colder Than Canada?
जटिल पैटर्न के लिए re.sub()
sub() का पहला आर्गुमेंट मिलान करने का पैटर्न है और दूसरा आर्गुमेंट रिप्लेसमेंट पैटर्न है।
नीचे उदाहरण में, हम dd/mm/yyyy फॉर्मेट में डेट फील्ड ढूंढेंगे और उन्हें yyyy-dd-mm फॉर्मेट में बदलेंगे। बैकस्लैश्ड डिजिट्स जैसे \3 पैटर्न में कैप्चर ग्रुप नंबर्स को संदर्भित करते हैं।
import re
sentence = 'Date is 22/11/2020. Tommorow is 23/11/2020.'
replaced_text = re.sub(r'(\d+)/(\d+)/(\d+)', r'\3-\1-\2', sentence)
print(f"Output \n {replaced_text}")
आउटपुट: Date is 2020-22-11. Tommorow is 2020-23-11.
बेहतर परफॉरमेंस के लिए एक्सप्रेशन कंपाइल करें
pattern = re.compile(r'(\d+)/(\d+)/(\d+)')
replaced_pattern = pattern.sub(r'\3-\1-\2', sentence)
print(f"Output \n {replaced_pattern}")
आउटपुट: Date is 2020-22-11. Tommorow is 2020-23-11.
re.subn() - सब्स्टीट्यूशन की संख्या भी प्राप्त करें
output, count = pattern.subn(r'\3-\1-\2', sentence)
print(f"Output \n {output}")
print(f"Output \n {count}")
आउटपुट: Date is 2020-22-11. Tommorow is 2020-23-11.
2