1:compile()编译正则表达式
python的代码最终会被编译为字节码,然后才被解释器执行,在模式匹配之前,正则表达式必须先被编译成regex对象,由于正则表达式在执行过程中被多次用于比较,所以强烈建议进行预编译
2:match()从字符串开头开始对模式进行匹配,匹配成功返回匹配对象,匹配不成功返回None
import re
m=re.match('foo','foodefew')
print '匹配对象m:',m
j=re.match('foo','seafood')
print '匹配对象j:',j
n=re.match('foo','bar')
print '匹配对象n:',n
3:group()返回匹配对象,或者是根据需求返回某个特定子组
if m is not None:
m.group()
print m.group()
4:search()在一个字符串中查找一个模式
search=re.search('foo','seafood')
print '匹配对象search:',search
5:匹配多个字符串(|)
bt='bat|bet|bit'
m=re.match(bt,'bat')
print '匹配对象m:',m
n=re.match(bt,'is bit?')
print '匹配对象n:',n
search=re.search(bt,'is bit?')
print '匹配对象search:',search
6:匹配任意单个字符(.),如果要匹配(“.”)需要使用转义符
tmpStr='.end'
m=re.match(tmpStr,'tend')
print '匹配对象m:',m
n=re.match(tmpStr,'end')
print '匹配对象n:',n
t=re.match(tmpStr,'\nend')#一些特殊符号
print '匹配对象t:',t
search=re.search(tmpStr,'is end!')
print '匹配对象search:',search
#匹配(".")需要使用转义符
pi='3\.14'
p=re.match(pi,'3.14')
print '匹配对象p:',p
7:创建字符集合
regex='[cr][23][dp][o2]'
m=re.match(regex,'c2p2')
print '匹配对象m:',m
8:重复,特殊字符和子组
patt='\w+@(\w+\.)?\w+\.com'
m=re.match(patt,'no@gmail.com')
print '匹配对象m:',m
n=re.match('\w\w\w-\d\d\d','abc-123')
print '匹配对象n:',n
#无子组
noGroup=re.match('ab','ab').groups()
print '无子组:',noGroup
isGroup=re.match('(ab)','ab').groups()
print '有子组:',isGroup
isGroup=re.match('(a(b))','ab').groups()
print '有子组:',isGroup
9:从字符串的开头或结尾匹配及在单词边界上的匹配
#匹配
m=re.search('^the','the house.')
print '匹配对象m:',m
#不在开头
m=re.search('^the','i have the ball!')
print '不在开头m:',m
#在词边界
m=re.search(r'\bthe','bite the dog')
print '在词边界m:',m
#不在词边界
m=re.search(r'\bthe','bite hthe dog')
print '不在词边界m:',m
10:findall()用于非重叠地搜索某字符串中一个正则表达式模式出现的情况,它和search()都是执行搜索,但是findall()总返回一个列表,如果没有找到匹配的部分,会返回空列表
f=re.findall('car','car')
print f
f=re.findall('car','carray')
print f
f=re.findall('car','carry the barcardi to the car')
print f
11:sub()/subn()都是搜索和替换的功能,区别就是subn()会返回一个表示替换次数的数字
s=re.sub('x','Melin','/x/user/tmp')
print s
s=re.subn('[ae]','x','abcdef')
print s
12:分割模式split()
s=re.split(':','str1:str2:str3')
print s
Python群:298948196