八、Python:正则表达式

    在本章我们来一起了解下Python中的正则表达式的使用方式

 

一、re.match的函数原型为:re.match(pattern, string, flags) 只匹配字符串的开头

# -*- coding: gb18030 -*- 

#例1:
import re  
text = "china,Hello"  
m = re.match("china", text)  

if m is not None:  
    print m.group()
else:  
    print 'not match'  
#输出 => china

    
#例2:
pattn = ".end"
m = re.match(pattn," end")  
if m is not None:
    print 'result:' + m.group()
else:
    print 'not match'
#输出 => result: end


二、re.search re.search(pattern, string, flags) 从左到右开始匹配字符串

# -*- coding: gb18030 -*- 

import re
text = "Hello china"  
m = re.search("china", text)  
if m is not None:  
    print 'result:' + m.group() 
else:  
    print 'not search'  
    
# 输出=> result:china

 

三、搜索并替换 re.sub() 或re.subn()

# -*- coding: gb18030 -*- 

import re

print re.sub("B","I","CHBNA")               #输出=> CHINA
print re.subn("B","I","CHBNA")              #输出=>('CHINA',1),1表示替换次数

 

四、split

# -*- coding: gb18030 -*- 

import re
print re.split(",","a,b,c")           #=>输出['a', 'b', 'c']
print "a,b,c".split(",")              #=>输出['a', 'b', 'c']
print re.split("\s\w{2}","1 aa2 bb3") #=>输出['1', '2', '3']


五、综合

# -*- coding: gb18030 -*- 
import re

pattn = "^[ab]\w{3,4}\d+"  #匹配以a或b开头,后面3或4个字母,再接1个或多个数字
li = ["aabb123","bbaba456","bcdefghi789","abce"]

for i in range(0,len(li)):
    m = re.search(pattn,li[i]) 
    
    if m is not None:
        print 'result:' + m.group()
    else:
        print 'not match'

'''
 输出如下结果=>:
result:aabb123
result:bbaba456
not match
not match
'''




 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值