提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
提示:这里可以添加本文要记录的大概内容:
python正则匹配学习记录
一、元字符
元字符:具有固定含义的特殊符合
正则在线网址 https://tool.oschina.net/regex/?optionGlobl=global#
常用元字符:
. 匹配一个除换行服的任意字符
\w 匹配一个字母或数字或下划线 0-9 z-z A-Z _
\d 匹配一个数字 0-9
\s 匹配一个空白符 换行 回车 空格 \t 爬虫一般不用
\t 匹配一个制表符
\W 匹配一个非字母或数字或下划线
\S 匹配一个非数字
\D 匹配一个非空白符
a|b 匹配字符a或者b
^ 匹配字符串的开始 以什么开始 如 ^ab 以a开始
$ 匹配字符串的结尾 以什么结束 如 ad$ 以d结束
^\d\da$ 以数字开始以字母a结束 13a 45a 78a
() 匹配括号内的表达式 也表示一个组
[...] 匹配字符组中的字符 如[abc] 匹配a或b或c
[^...] 匹配除了字符组中字符的所有字符
量词:控制前面的元字符出现的次数
* 重复零次或更多次
+ 重复一次或更多次
? 重复零次或一次
{n} 重复n次
{n,} 重复n次或更多次
{n,m}重复n到m次
贪婪匹配和惰性匹配
.* 贪婪匹配,尽可能多的去匹配结果
.*? 惰性匹配,尽可能少的去匹配结果
二、re模块基本使用方法
import re
# 利用正则表达式搜索
# search 从前到后匹配,遇到匹配的内容,直接结束,返回
result = re.search(r"\d","我今天吃了3个糖果,喝了2盒酸奶")
# search的结果被封装在Match对象里
print(result) # <re.Match object; span=(5, 6), match='3'>
# 想要结果. 需要.group()
print(result.group()) # 3
# findall直接把匹配的结果返回. 放在列表里
result = re.findall(r"\d","我今天吃了3个糖果,喝了2盒酸奶")
print(result) # ['3', '2']
# re.finditer 性能上好,返回一个迭代器对象,循环提取可得到结果
result = re.finditer(r"\d","我今天吃了3个糖果,喝了2盒酸奶")
print(result) # <callable_iterator object at 0x000001B57F799F40>
for item in result:
print(item.group()) # 3 2
# 提前定义正则
obj = re.compile(r"\d+")
# 随时匹配
result = obj.search("我喜欢你18年了")
print(result) # <re.Match object; span=(4, 6), match='18'>
print(result.group()) # 18
result = obj.search("你喜欢我2年了")
print(result) # <re.Match object; span=(4, 5), match='2'>
print(result.group()) # 2
三、python正则匹配字符串练习
import re
import json
# 练习
s = """
<div class='西游记'><span id='10010'>中国电信1</span></div>
<div class='三国演义'><span id='10011'>中国电信2</span></div>
<div class='水浒传'><span id='10012'>中国电信3</span></div>
<div class='金瓶梅'><span id='10013'>中国电信4</span></div>
"""
# 一条一条的获取到数据
# 西游记,10010,中国1
# (?P<>.*?)分组起名字
obj = re.compile(r"<div class='(?P<shu>.*?)'><span id='(?P<id>.*?)'>(?P<zg>.*?)</span></div>")
result = obj.finditer(s)
for item in result:
shu = item.group('shu')
id = item.group('id')
zg = item.group('zg')
print(shu,id,zg)
# 字符串替换
s = " 基础不牢\r, 地动山摇\n \t ..."
r = s.replace(" ","").replace("\r","").replace("\t","").replace("\n","")
print(r) # 基础不牢,地动山摇...
# \s匹配空白符 替换为"" re.sub(正则,"替换为什么","原字符串")
r2 = re.sub(r"\s", "", s)
print(r2) # 基础不牢,地动山摇...
# 练习处理jsonp数据
s = """data_callback([
{
"title":"特朗普和泽连斯基吵了些什么 更多细节披露",
"digest":"",
"docurl":"https://www.163.com/dy/article/JPI6840J0514R9OJ.html",
"commenturl":"https://comment.tie.163.com/JPI6840J0514R9OJ.html",
"tienum":3082,
"tlastid":"",
"tlink":"https://www.163.com/dy/article/JPI6840J0514R9OJ.html",
"label":"其它",
"keywords":[
],
"time":"03/01/2025 08:31:52",
"newstype":"article",
"pics3":[
],
"channelname":"guoji",
"source":"环球网资讯",
"point":"60",
"imgurl":"http://cms-bucket.ws.126.net/2025/0301/e22a68c1p00ssf5la000xc0009c0070c.png",
"add1":"",
"add2":"",
"add3":""
}
])"""
# 加上re.S, 可以让正则表达式匹配换行符
# matches any character at all, including the newline
obj = re.compile(r"data_callback\((?P<data>.*?)\)",re.S)
r = obj.search(s)
# print(r.group("data"))
# 把字符串处理成python字典
print(json.loads(r.group("data")))
四、python正则匹配豆瓣html练习
import re
"""
排名,名称,导演,主演,评分
"""
f = open('top250.html',mode="r",encoding="utf-8")
content = f.read()
f.close()
obj = re.compile(r'<div class="item">.*?<e'
r'm class="">(?P<rank>.*?)</em>.*?<span class="title">(?P<name>.*?)</span>.*?导'
r'演: (?P<dao>.*?) .*?主演: (?P<zhu>.*?)...<br>.*?<sp'
r'an class="rating_num" property="v:average">(?P<score>.*?)</span>',re.S)
r = obj.finditer(content)
for item in r:
rank = item.group("rank")
name = item.group("name")
dao = item.group("dao")
zhu = item.group("zhu")
score = item.group("score")
# conment = item.group("comment")
print(rank, name, dao, zhu,score)
# print(r.group("rank"))
总结
js返回的jsonp数据,re能好提取