रेगेक्स [डुप्लिकेट] का उपयोग करके अजगर में एक स्ट्रिंग से शब्द के रूप में लाने के लिए कैसे
Nov 25 2020
मेरे पास एक तार जैसा है
string = "Status\t\t: PASS"
मैं इस स्ट्रिंग से केवल पास प्राप्त करना चाहता हूं और मैं इस regex का उपयोग कर रहा हूं।
value = re.findall("Status" + r'(.*)', string)
लेकिन यह मुझे यह लौटाता है
" : PASS"
मैं चाहता हूं कि रेगेक्स सभी अतिरिक्त वर्ण स्थान टैब आदि को अनदेखा करे। कृपया मुझे बताएं कि मैं यह कैसे कर सकता हूं।
जवाब
3 VivekKumar Nov 25 2020 at 13:36
विधि: regex () + string.punctuation का उपयोग करते हुए इस पद्धति में नियमित अभिव्यक्तियों का भी उपयोग किया गया, लेकिन सभी विराम चिह्न प्राप्त करने के स्ट्रिंग फ़ंक्शन का उपयोग सभी विराम चिह्नों को अनदेखा करने और फ़िल्टर किए गए परिणाम स्ट्रिंग प्राप्त करने के लिए किया जाता है।
# Python3 code to demonstrate
# to extract words from string
# using regex() + string.punctuation
import re
import string
# initializing string
test_string = "Geeksforgeeks, is best @# Computer Science Portal.!!!"
# printing original string
print ("The original string is : " + test_string)
# using regex() + string.punctuation
# to extract words from string
res = re.sub('['+string.punctuation+']', '', test_string).split()
# printing result
print ("The list of words is : " + str(res))
आउटपुट:
The original string is : Geeksforgeeks, is best @# Computer Science Portal.!!!
The list of words is : [‘Geeksforgeeks’, ‘is’, ‘best’, ‘Computer’, ‘Science’, ‘Portal’]
2 tshiono Nov 25 2020 at 14:25
क्या आप निम्नलिखित प्रयास करेंगे:
import re
string = "Status\t\t: PASS"
m = re.search(r'Status\s*:\s*(.*)', string)
print(m.group(1))
आउटपुट:
PASS
रेगेक्स की व्याख्या Status\s*:\s*(.*)
:
Status\s*
"स्थिति" के विकल्प से मेल खाता है और यदि संभव हो तो रिक्त वर्णों का अनुसरण कर सकता है।:\s*
एक चरित्र ":" से मेल खाता है और यदि संभव हो तो खाली वर्णों का पालन करें।(.*)
शेष सबरिंग और कैप्चर समूह 1 से मेल खाता है।
1 Heo Nov 25 2020 at 14:23
इसे आज़माएँ: रेगेक्स-डेमो
पायथन-स्रोत:
import re
input1 = "Status\t\t: PASS"
input2 = "Status\t\t: PASS hello"
input3 = "Status\t\t: FAIL hello world"
regex=re.compile('status\s*:\s*(\w+)',flags=re.IGNORECASE)
print(f'result of input1: \n {regex.findall(input1)}')
print(f'result of input2: \n {regex.findall(input2)}')
print(f'result of input3: \n {regex.findall(input3)}')
आउट-पुट:
result of input1:
['PASS']
result of input2:
['PASS']
result of input3:
['FAIL']