python實戰系列之正則獲取IP地址(八)

1.正則表達式repython

 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例子shell

1.匹配數字bash

>>> 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. 匹配shellide

>>> f = file('/etc/passwd','r')                函數

>>> for line in f.readlines():                 spa

...     re.findall('\/bin\/[a-z]*sh$',line.strip())ip

... 字符串

['/bin/bash']get

[]

[]

['/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地址

相關文章
相關標籤/搜索