आप मिलान समूहों का उपयोग कर सकते हैं:
p = re.compile('name (.*) is valid')
जैसे
>>> import re
>>> p = re.compile('name (.*) is valid')
>>> s = """
... someline abc
... someother line
... name my_user_name is valid
... some more lines"""
>>> p.findall(s)
['my_user_name']
यहाँ मैं के re.findallबजाय re.searchसभी उदाहरण प्राप्त करने के लिए उपयोग करते हैं my_user_name। का उपयोग करते हुए re.search, आपको मैच ऑब्जेक्ट पर समूह से डेटा प्राप्त करने की आवश्यकता होगी:
>>> p.search(s) #gives a match object or None if no match is found
<_sre.SRE_Match object at 0xf5c60>
>>> p.search(s).group() #entire string that matched
'name my_user_name is valid'
>>> p.search(s).group(1) #first group that match in the string that matched
'my_user_name'
जैसा कि टिप्पणियों में बताया गया है, आप अपने रेगेक्स को गैर-लालची बनाना चाहते हैं:
p = re.compile('name (.*?) is valid')
केवल 'name 'और अपने समूह में ' is valid'अन्य लेने के लिए अपने regex अनुमति देने के बजाय अगले और अगले सामान लेने के लिए ' is valid'।
group(0)पहले मैच के लिए नहीं हैं ?