1 str ='purple [email protected] monkey dishwasher' 2 match = re.search('([\w.-]+)@([\w.-]+)', str) 3 if match: 4 print match.group() ## '[email protected]' (the whole match) 5 print match.group(1) ## 'alice-b' (the username, group 1) 6 print match.group(2) ## 'google.com' (the host, group 2)
用()区分各个分组
1 str ='purple [email protected], blah monkey [email protected] blah dishwasher' 2 ## re.sub(pat, replacement, str) -- returns new string with all replacements, 3 ## \1 is group(1), \2 group(2) in the replacement 4 print re.sub(r'([\w\.-]+)@([\w\.-]+)', r'\[email protected]', str) 5 ## purple [email protected], blah monkey [email protected] blah dishwasher