import re
\d 数字
\w 字母或数字
\s 1个空格(含tab)
. 任意单个字符
* 任意长度字符(含0个)
+ 至少1个字符
? 0或1个字符
{n-m} n-m个字符
(P|p)ython 'Python'或者'python'
[a-zA-Z\_][0-9a-zA-Z\_]{0, 19}:由字母或下划线开头,后接最多19个由数字、字母或者下划线组成的字符串
^ 在开头表示“以……开头”,在[]之间表示“非”
#匹配
re.match(r'^\d{3}\-\d{3,8}$', '010-12345') #匹配返回match对象,否则返回None
#分组
m = re.match(r'^(\d{3})-(\d{3,8})$', '010-12345')
m.groups() #('010', '12345')
m.group(0) #'010-12345'
m.group(1) #'010'
m.group(2) #'12345'
#替换
import re
text = "JGood is a handsome boy, he is cool, clever, and so on..."
print re.sub(r'\s+', '-', text)
txt=re.compile(r'<[^>]+>').sub('', html) #去除html标记
#切分
'a b c'.split(' ') #-->['a', 'b', '', '', 'c'] 字符串自带函数,未应用正则
re.split(r'\s+', 'a b c') #-->['a', 'b', 'c']
re.split(r'[\s\,\;]+', 'a,b;; c d') #-->['a', 'b', 'c', 'd']
words=re.compile(r'[^A-Z^a-z]+').split(txt) #利用非字母字符拆分出单饲
words=re.compile('\\W*').split(txt) #利用非字母、数字字符拆分出单饲
#编译
re_telephone = re.compile(r'^(\d{3})-(\d{3,8})$')
re_telephone.match('010-12345').groups() #('010', '12345')
#匹配中文
source = "s2f程序员杂志一2d3程序员杂志二2d3程序员杂志三2d3程序员杂志四2d3"
temp = source.decode('utf8')
pattern = re.compile(u"([\u4e00-\u9fa5]+)")
results = pattern.findall(temp)
for result in results :
print result