re的使用
- 正则表达式是一个特殊的字符序列,它能帮你方便的检查一个字符串是否与某种模式匹配
- python自1.5版本起增加了re模块,它提供perl风格的正则表达式模式。
- re模块使python语言拥有全部的正则表达式功能。
re.match函数
re.match尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功,match()返回none
re.search方法
re.search扫描整个字符串并返回第一个成功的匹配。
re.match与re.search的区别
re.match只匹配字符串的开始,如果开始不符合正则表达式,就匹配失败,函数返回none;
re.search匹配整个字符串,直到找到一个匹配。
import re
print("hello world")
print(re.match("hello","hello world"))
print(re.match("world","hello world"))
hello world
<_sre.SRE_Match object; span=(0, 5), match='hello'>
None
print(re.search("hello","hello world"))
print(re.search("world","hello world"))
<_sre.SRE_Match object; span=(0, 5), match='hello'>
<_sre.SRE_Match object; span=(6, 11), match='world'>
# 查询数字 \d
str1="123好家伙"
print(re.match("\d",str1))
print(re.match("\d\d\d",str1))
# + 代表至少出现一次
print(re.match("\d+",str1))
# * 字符串中没有的话也显示找到,只不过显示0-0,一般不用*,用+
# str2="asdf"
# print(re.search("\d*"),str2)
<_sre.SRE_Match object; span=(0, 1), match='1'>
<_sre.SRE_Match object; span=(0, 3), match='123'>
<_sre.SRE_Match object; span=(0, 3), match='123'>
str1="12是12 是好家伙"
print(re.match("\d+",str1).start())
print(re.match("\d+",str1).end())
0
2
#省略某部分
str2="cat is smarter than dog"
r=re.match("(.*) is smarter than",str2)
print(r)
<_sre.SRE_Match object; span=(0, 19), match='cat is smarter than'>
#取出某部分
r=re.match("(.*) is (.*) than",str2)
print(r)
print(r.group(2))
<_sre.SRE_Match object; span=(0, 19), match='cat is smarter than'>
smarter
修饰器
装饰器是一个著名的设计模式,经常被用于有切面需求的场景,较为经典的有插入日志、性能测试、事务处理等。装饰器是解决这类问题的绝佳设计,有了装饰器,我们就可以抽离出大量函数中与函数功能本身无关的雷同代码并继续重用。概括的讲,装饰器的作用就是为已经存在的对象添加额外的功能。
import time
def food():
print("开饭了 , 干饭人")
#直接在内部修改
def food():
start = time.clock()
print("开饭了 , 干饭人")
time.sleep(0.3)
end =time.clock()
print("耗时为",str(end-start))
food()
#修饰器第一种
import time
def food():
print("开饭了 , 干饭人")
def timeit(f):
def wrapper():
start = time.clock()
time.sleep(0.3)
f()
end = time.clock()
print("耗时为", str(end-start))
return wrapper
newfood=timeit(food)
newfood()
#修饰器第二种
import time
def timeit(f):
def wrapper():
start = time.clock()
time.sleep(0.3)
f()
end = time.clock()
print("耗时为", str(end-start))
return wrapper
@timeit
def food():
print("开饭了 , 干饭人")
food()