码迷,mamicode.com
首页 > 编程语言 > 详细

Python正则表达式(二)

时间:2017-07-12 16:49:20      阅读:260      评论:0      收藏:0      [点我收藏+]

标签:搜索   ring   正则表达   split()   字符串   pytho   color   bsp   sub   

sub()和subn()  sub(pattern,repl,string,count=0)   用于实现搜索和替换功能, 使用repl替换所有正则表达式的模式在字符串中出现的位置,除非定义count,否则将替换所有出现的位置。用来替换的部分通常是一个字符串,也可能是一个返回字符串的函数。sub()还将返回发生替换的总数,并将和替换后的字符串以两个元素元组返回。

m = re.sub(‘t‘,‘T‘,‘this and that‘)
print 1,m

m = re.subn(‘[ae]‘,‘X‘,‘abcdef‘)
print 2,m

d = re.sub(r‘(\d{1,2})/(\d{1,2})/(\d{2}|\d{4})‘,r‘\2/\1/\3‘,‘11月/21日/1995年‘)
print 3,d


1 This and ThaT
2 (‘XbcdXf‘, 2)
3 11月/21日/1995年

 

split() 分割字符串:

re.split(‘:‘,‘str1:str2:str3‘)


[‘str1‘, ‘str2‘, ‘str3‘]

 

Python正则表达式(二)

标签:搜索   ring   正则表达   split()   字符串   pytho   color   bsp   sub   

原文地址:http://www.cnblogs.com/pythonabc/p/7156271.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!