1.正则表达式re
python中通过re模块实现正则表达式相关的功能,正则是一种模式匹配patter,通过模式匹配,实现对字符的搜索search和匹配match功能,正则表达式常用的原字符包括:
原字符 | 代表含义 |
literal | 代表字符串本身,如'hello' |
. | 任意字符 |
^ | 匹配字符串的开头 |
$ | 匹配字符串的结尾 |
* | 匹配前面的正则表达式0次或者多次,相当于{0,} |
+ | 匹配前面的正则表达式1次或者多次,相当于{1,} |
? | 匹配前面的正则表达式0次或者1次,相当于{0,1} |
{M,N} | 匹配前面的正则表达式最少M次,最多N次 |
{N} | 匹配前面的正则表达式至少N次,相当于{N,} |
[] | 匹配字符串组里面的任意一个字符,如[0-9],[a-z],[a-zA-Z] |
[^] | 排除字符串组里面的任意字符,如[^a-zA-Z]表示排除所有的字母 |
\d | 匹配数字,相当于[0-9],如data\d.txt |
\D | 和\d相反,相当于[^0-9] |
\w | 匹配字母和数字,相当于[a-zA-Z0-9],如\w+ |
\W | 排除字母和数字,相当于[^a-zA-Z0-9] |
\s | 空白符,包括tab,回车,相当于[\t\n\r\v\f] |
2.正则表达式re例子
1.匹配数字
>>> import commands >>> network = commands.getstatusoutput('ifconfig') >>> import re >>> re.findall('[0-9]+',network[1]) #搜索了所有的数字,用\d+效果和上面相同 >>> re.findall('\d+',network[1]) 扩展1:通过正则匹配各位数 >>> re.findall('\d',network[1]) 扩展2:通过正则匹配0-99之间的数字,0-9之间的数字可以用[0-9]表示,10-99之间的数字可以用[1-9]{1,2},和在一起就是[0-9]{1,2} >>> re.findall('[0-9]{1,2}',network[1]) 扩展3:通过正则匹配0-255之间的数字,可以分为四段:0-99使用[0-9]{1,2},100,199使用1[0-9][0-9],200-249使用2[0-4][0-9],250-255使用25[0-5]来表示 >>> re.findall('[0-9]{1,2}|1[0-9][0-9]|2[0-4][0-9]|25[0-5]',network[1])
2. 匹配shell
>>> f = file('/etc/passwd','r')
>>> for line in f.readlines():
... re.findall('\/bin\/[a-z]*sh$',line.strip())
...
['/bin/bash']
[]
[]
['/bin/bash']
[]
['/bin/bash']
3. re模块常用方法
re是python实现正则表达式相关功能的模块,该模块包含多重方法,常见的方法包括:搜索search(),匹配match,查找所有findall(),编译compile(),切割split(),查找替换sub()等方法,下面开始介绍:
1. match(),匹配,从字符串的起始位开始搜索,找到则返回,没找到则为空
>>> str = 'Hello python boys' >>> if m is not None: ... print "匹配了字符串的起始关键字" ... print "匹配的字符串是:%s" % (m.group()) ... else: ... print "不匹配" ... 匹配了字符串的起始关键字 匹配的字符串是:Hello #如果不匹配的话 >>> m = re.match('python',str) >>> print m None >>> if m: ... print "match,string is:%s" % (m.group()) ... else: ... print "not match" ... not match @@注意,使用match()和search()函数,如果模式匹配成功的话,则模式会具有group()方法,即显示模式匹配成功的字符串,需要注意的是:match()函数从最开始匹配,而search()则是全文搜索
2.search(),从字符串的开始到结尾搜索,查到则返回,没找到则空
>>> m = re.search('python',str) >>> print m <_sre.SRE_Match object at 0x1e37b28> >>> if m: ... print "match,string is:%s" % (m.group()) ... else: ... print "not match" ... match,string is:python
3. compile(),编译正则表达式,方便重复使用,需要配配合search(),match(),findall()函数使用
>>> regex=re.compile('python') >>> regex.search(str) <_sre.SRE_Match object at 0x1e37bf8> >>> m = regex.search(str) >>> print m <_sre.SRE_Match object at 0x1e37c60> >>> if m: ... print "match,string:%s" % (m.group()) ... else: ... print "not match" ... match,string:python >>> m=regex.match(str) >>> print m None
4.findall(),从所有的字符串中查找,找到则加入到列表中,以列表的形式显示,如果没找到则列表为空
>>> re.findall('o',str) ['o', 'o', 'o'] 正则编译形式: >>> regex=re.compile('o') >>> regex.findall(str) ['o', 'o', 'o']
4.正则表达式获取IP地址