---
title: "python找出一串字符中所有的email"
author: "ice_cube"
date: "2010-06-11T16:42:04Z"
tags: []
categories: ["编程语言"]
slug: "python-email"
draft: false
lastmod: "2010-06-11T16:42:04Z"
id: 689919
url: "https://ice-cube.iteye.com/blog/689919"
---

```python

#coding=utf-8
import re
email_re = re.compile(
    r"(([-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*"  # dot-atom
    r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-011\013\014\016-\177])*"' # quoted-string
    r')@(?:[a-z0-9]+(?:-*[a-z0-9]+)*\.)+[a-z]{2,6})', re.IGNORECASE)  # domain

email_str = u"aabbcc@163.com　　ＱＱ：８７５９００６７ MSN:ddeedd@hotmail.com"

email_list = []

for one in email_re.findall(email_str):
    email_list.append(one[0]) 

print email_list

```


结果：

其中email_re为django源码中匹配email地址的正则表达式

注：
区分group,groups,findall:

group()即默认情况， 是返回的整个表达式所匹配的，group(1)是返回子组1（其实就是第一个括号里的表达式）所匹配的，类似的group(2)是子组2匹配的，为了方面记忆，可以用命名组 (?P<name>...) 匹配时用group(name)即可

而groups()返回的是一个元组，包括所有子组所匹配的 如 (子组1,子组2,...)

而findall()返回的是一个列表，他的第一个元素其实就是groups()返回的元组

一个简单的例子：


```python

>>> re.search('(a(\d))','a342a1').group(0,1,2)
('a3', 'a3', '3')
>>> re.search('(a(\d))','a342a1').groups()
('a3', '3')
>>> re.findall('(a(\d))','a342a1')
[('a3', '3'), ('a1', '1')]

```