这里写反斜杠也是转义的意思,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