import re
t='_@#$'
ret=re.match('[^1-9]+',t)
print(ret.group())
# #匹配任意字符,除换行符等
t='wewq'
ret=re.match('.',t)
print(ret.group())
t=' '
ret=re.match('\s',t)
print(ret.group())
t='_wqQ'
ret=re.match('\S+',t)
print(ret.group())
t='_@#$'
ret=re.match('[^1-9]+',t)
print(ret.group())
t='aaaADSDSAF_@#$'
ret=re.match('\w{6}',t)
print(ret.group())
t='aaa'
ret=re.match('\w{2,6}',t)
print(ret.group())
#邮箱
t='1539664389@qq.com'
ret=re.match('\d+@[a-z0-9]+\.\w+',t)
print(ret.group())
# #URL
t='https://blog.csdn.net/weixin_49265805/article/details/112771325'
ret=re.match('\w+://[._0-9/a-z]+',t)
print(ret.group())
#以什么结尾
t='112771325@qq.com'
ret=re.match('\d+@\w+.com$',t)
print(ret.group())
#匹配多个字符串或表达式
t='http'
ret=re.match('(fyp|http)$',t)
print(ret.group())
#贪婪模式和非贪婪模式
t='99'
ret=re.match('\w+?',t)
print(ret.group())
#Re函数
t='www@www'
ret=re.search('\w+\@\w+',t)
print(ret.group())
t='\\n'
ret=re.search('\\\\n',t)
print(ret.group())
t='\c'
ret=re.match(r'\\c',t)
print(ret.group())
#分组
t='aaaa sdsf$10 dfdsgsd$109 safafwe'
ret=re.search('.*(\$\d+).*(\$\d+)',t)
print(ret.group(1))
print(ret.group(2))
print(ret.groups())
#findall查找所有合适的结果,并返回列表
t='aaaa sdsf$10 dfdsgsd$109 safafwe'
ret=re.findall('\w+',t)
print(ret)
#替换
t='aaaa sdsf$10 dfdsgsd$109 safafwe'
ret=re.sub('\$\d+','999',t)
print(ret)
#分割split
t='aaaa1ad3sd4sffsafafwe'
ret=re.split('[a-z]',t)
print(ret)
#compile 提升效率
t='aaaa1ad3sd4sffsafafwe'
ret=re.compile('\w+\d+')
r=re.search(ret,t)
print(r.group())
t='aaaa1ad3sd4sffsafafwe'
ret=re.compile(r'''
\w+#匹配字母
\d+#匹配数字
''',re.VERBOSE)
r=re.search(ret,t)
print(r.group())
糗事百科爬取练习
import requests
import re
url = "https://www.qiushibaike.com/text/"
payload={}
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36'
}
response = requests.request("GET", url, headers=headers)
h=response.text
pattern = re.findall(r'<a οnclick=".*?">\n<h2>\n(.*?)\n</h2>\n</a>',h,re.S)
pinlub=re.findall(r'<span class="cmt-name">(.*?):</span>',h,re.S)
neirun=re.findall(r'<div class="content">\n<span>\n(.*?)\n</span>\n.*?</div>',h,re.S)
for i in neirun:
jia=re.sub('<br/>',' ',i)
print(jia)