python re模块的学习

来源:互联网 发布:最好的淘宝客程序 编辑:程序博客网 时间:2024/04/30 00:22

re模块是用来处理正则表达式的,正则表达式几乎在每一门语言中都有,用处可谓很大,主要用与搜索、匹配和替代,向邮箱、手机号码的匹配,搜索对应的文件名并进行替换等,下边稍微罗列一下python常用的re模块中的相关函数,基本符号的使用这里就不说了

1、re.match与re.search,查找字符串

      re.match从字符串的开头查找匹配的字符
      re.search从字符串的任意位置查找匹配字符

import retest = "Click the button!"matchstr = re.match("the",test)if matchstr is None:    print "matchstr is None"searchstr = re.search("the",test)if searchstr is not None:    print searchstr.group()
结果显示:


2、re.sub替换字符串

      re.sub(arg1,arg2,arg3) 说明:arg3中的arg1被arg2替换

import retext = "I Love C++"# 文字替换 (string.replace 速度更快)print re.sub("C\+\+", "Python", text)#将空白字符转换为[tab]print re.sub("\s+", "[tab]", text)# 将所有单词替换为 wordprint re.sub("\S+", "word", text)
结果显示:

3、re.compile

      将正则表达式编译为一个对象,这样执行起来更快

import reimport stringtext = "I Love C++"temp = re.compile("C\+\+")print temp.sub("Python",text)
结果显示:


4、re.findall

       查找所有匹配的字符串,返回结果为一个列表

import reimport stringtext = "ice@163.com word@163.com hello99@163.com word@gmail.com python@126.cn"temp = re.compile("[a-z]+@\d{3}.com")

结果显示:



5、re.split

      用正则表达式切割字符串

import reimport stringtext = "12:29:56"temp = re.compile(":")print temp.split(text)print temp.findall(text)

结果显示:



0 0