3', 'ababab123')) # findall的结果不是匹配的全部内容,而是组内的内容,?:可以让结果为匹配的全部内容
print(re.findall('href="(.*?)"', '<a href="http://www.baidu.com">点击</a>')) # ['http://www.baidu.com']
print(re.findall('href="(?:.*?)"', '<a href="http://www.baidu.com">点击</a>')) # ['href="http://www.baidu.com"']
# |
print(re.findall('compan(?:y|ies)', 'Too many companies have gone bankrupt, and the next one is my company'))
import re
print(re.findall("<(?P<tag_name>\w+)>\w+</(?P=tag_name)>", "<h1>hello</h1>"))
print(re.search("<(?P<tag_name>\w+)>\w+</(?P=tag_name)>", "<h1>hello</h1>"))
print(re.search("<(?P<tag_name>\w+)>\w+</(?P=tag_name)>", "<h1>hello</h1>").group('tag_name'))
print(re.search(r"<(\w+)>\w+</\1>", "<h1>hello</h1>"))
# ['h1']
# <re.Match object; span=(0, 14), match='<h1>hello</h1>'>
# h1
# <re.Match object; span=(0, 14), match='<h1>hello</h1>'>
#匹配出所有的整数
import re
#ret=re.findall(r"\d+{0}]","1-2*(60+(-40.35/5)-(-4*3))")
ret=re.findall(r"-?\d+\.\d*|(-?\d+)","1-2*(60+(-40.35/5)-(-4*3))")
ret.remove("")
print(ret)
3. 常用方法
import re
#1
re.findall('a','alvin yuan') #返回所有满足匹配条件的结果,放在列表里
#2
re.search('a','alvin yuan').group() #函数会在字符串内查找模式匹配,只到找到第一个匹配然后返回一个包含匹配信息的对象,该对象可以
# 通过调用group()方法得到匹配的字符串,如果字符串没有匹配,则返回None。
#3
re.match('a','abc').group() #同search,不过尽在字符串开始处进行匹配
#4
ret=re.split('[ab]','abcd') #先按'a'分割得到''和'bcd',在对''和'bcd'分别按'b'分割
print(ret)#['', '', 'cd']
#5
ret=re.sub('\d','abc','alvin5yuan6',1)
print(ret)#alvinabcyuan6
ret=re.subn('\d','abc','alvin5yuan6')
print(ret)#('alvinabcyuanabc', 2)
#6
obj=re.compile('\d{3}')
ret=obj.search('abc123eeee')
print(ret.group())#123
1
2
3
4
5
6
import re
ret=re.finditer('\d','ds3sy4784a')
print(ret) #<callable_iterator object at 0x10195f940>
print(next(ret).group())
print(next(ret).group())
九、logging模块
1. 日志级别
CRITICAL = 50 #FATAL = CRITICAL
ERROR = 40
WARNING = 30 #WARN = WARNING
INFO = 20
DEBUG = 10
NOTSET = 0 #不设置
默认只会打印出warning以上级别的信息
2. 基础配置
import logging
logging.basicConfig( # 基础设置
level=logging.DEBUG, # 设置rootlogger的日志级别
filename='logger.log', # 用指定的文件名创建FiledHandler,这样日志会被存储在指定的文件中
filemode='w', # 文件打开方式,在指定了filename时使用这个参数,默认值为“a”还可指定为“w”。
format='%(asctime)s %(filename)s [%(lineno)d] %(message)s' # 指定handler使用的日志显示格式。
# stream:用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件,默认为sys.stderr。
# 若同时列出了filename和stream两个参数,则stream参数会被忽略。
)
logging.debug('kjhk')
logging.error('nhdvh')
# format格式
# %(name)s:Logger的名字,并非用户名,详细查看
# %(levelno)s:数字形式的日志级别
# %(levelname)s:文本形式的日志级别
# %(pathname)s:调用日志输出函数的模块的完整路径名,可能没有
# %(filename)s:调用日志输出函数的模块的文件名
# %(module)s:调用日志输出函数的模块名
# %(funcName)s:调用日志输出函数的函数名
# %(lineno)d:调用日志输出函数的语句所在的代码行
# %(created)f:当前时间,用UNIX标准的表示时间的浮点数表示