Python re模块

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值