這裏寫反斜槓也是轉義的意思,python在re模塊中使用都須要加反斜槓python
他和match有相同的做用,可是有區別。他會在整個字符串內容中匹配,直到找到第一個相匹配的字符串。linux
他和match和search差很少,可是他是找出字符串中全部的正則表達式
import re result1 = re.match('\d+','dshfjasdsf23432dhfhsjdjfhjsd') if result1: print result1.group() result2 = re.search('\d+','dshfjasdsf23432dhfhsjdjfhjsd') print result2 print result2.group() result3 = re.findall('\d+','dshfjasdsf23432dhfhsjdjfhjsd34') print result3 #輸出結果: <_sre.SRE_Match object at 0x0000000002BFA510> 23432 ['23432', '34']
他和編譯生成的.pyc文件差很少,.pyc是爲了再次使用時快速調用。正則表達式也能夠通過編譯,編譯以後匹配其餘的也會加快匹配速度shell
com = re.compile('\d+') print type(com) 輸出結果: <type '_sre.SRE_Pattern'> 他返回了一個對象
com = re.compile('\d+') print com.findall('dshfjasdsf23432dhfhsjdjfhjsd34')
import re f = open('love.txt','r') feitian = f.read() f.close() print re.findall('a',feitian) ##也能夠一行一行的匹配 f = open("love.txt", "r") while True: line = f.readline() if line: line=line.strip() p=line.rfind('.') filename=line[0:p] print line else: break f.close() 輸出: ['a', 'a', 'a']
result2 = re.search('(\d+)\w*(\d+)','dshfjasdsf23432dhfhs23423jdjfhjsd') print result2.group() print result2.groups() #輸出結果: 23432dhfhs23423 ('23432', '3') #注意: 他不重複拿,這裏解釋一下爲何第二個輸出爲3,由於中間都被\w*接收了,這裏咱們在給一個例子 result2 = re.search('(\d+)dhfhs(\d+)','dshfjasdsf23432dhfhs23423jdjfhjsd') print result2.group() print result2.groups() 輸出結果: 23432dhfhs23423 ('23432', '23423')
import re ip = 'sdhflsdhfj1723.234.234234.df.34.1234.df.324.xc.3+dsf172.25.254.1 sdfjk2130sdkjf.sdjfs' result1 = re.findall('(?:\d{1,3}\.){3}\d{1,3}',ip) result2 = re.findall('[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}',ip) print result1 print result2 #輸出結果: ['172.25.254.1'] ['172.25.254.1']
import time print time.time() 1510923748.06 #計算從1970年1月1日到如今有多少秒 print time.gmtime() time.struct_time(tm_year=2017, tm_mon=11, tm_mday=17, tm_hour=13, tm_min=2, tm_sec=28, tm_wday=4, tm_yday=321, tm_isdst=0) 格式化成一個對象,他是當前的時間 print time.strftime('%Y%m%d') 20171117 輸出格式化以後的時間,他的格式化和linux同樣
print time.strptime('2017-11-17','%Y-%m-%d') time.struct_time(tm_year=2017, tm_mon=11, tm_mday=17, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=4, tm_yday=321, tm_isdst=-1) #將字符串轉化成結構化的時間格式 print time.localtime() print time.mktime(time.localtime()) time.struct_time(tm_year=2017, tm_mon=11, tm_mday=17, tm_hour=21, tm_min=17, tm_sec=57, tm_wday=4, tm_yday=321, tm_isdst=0) 1510924677.0 #結構化的時間轉化成時間戳的格式 #字符串格式的時間轉時間戳格式他不能直接轉,必需要中轉
第一部分時間戳形式存在,第二部分以結構化形式存在,第三部分以字符串形式存在windows