Python之正则表达式

目录


re.match

原型:

re.match(pattern, string, flags=0)
  • pattern:表达式
  • string:目标字符串
  • flags:匹配模式

从起始位置开始匹配,匹配成功返回字符串,失败返回none

常规匹配

  • ^ :表示以后面的字符开头
  • \s:代表一个空白字符
  • \d:代表任意一个数字同[0-9]
  • \d{3}:代表任意三个数字
  • \w{10}:代表10个任意字母数字和下划线
  • .:代表除了换行符任意字符
  • * :代表0个或者无数个前面的表达式
  • .*:表示0个或者无数个除换行符的任意字符
import re

content= "Hello 123 456 World_This is a Regex Demo"
result = re.match("^Hello\s\d\d\d\s\d{3}\s\w{10}.*Demo",content) 
print(result) #返回结果对象
print(result.group())#返回结果
<re.Match object; span=(0, 40), match='Hello 123 456 World_This is a Regex Demo'>
Hello 123 456 World_This is a Regex Demo

泛匹配

import re

content= "Hello 123 456 World_This is a Regex Demo"
result = re.match("^Hello.*Demo",content) 
print(result) #返回结果对象
print(result.group())#返回结果
<re.Match object; span=(0, 40), match='Hello 123 456 World_This is a Regex Demo'>
Hello 123 456 World_This is a Regex Demo

目标匹配

获取 Hello 123456 World_This is a Regex Demo 中的123456

  • \d+:表示一个或者多个数字
  • (\d+):表中group中的因素,第一个()中的内容即为group(1)
import re

content= "Hello 123456 World_This is a Regex Demo"
result = re.match("^Hello\s(\d+)\sWorld.*Demo$",content) 
print(result) #返回结果对象
print(result.group(1))#返回结果
<re.Match object; span=(0, 39), match='Hello 123456 World_This is a Regex Demo'>
123456

贪婪匹配

贪婪匹配会尽可能多的匹配字符,直到匹配不到,如下面例子,.* 会尽可能多的匹配任意字符,直到不能匹配,也就是后面的(\d+) 至少要一个字符。所以前面的12345 都被 .* 匹配了,而(\d+) 只匹配到一个6

  • .*:贪婪模式
import re

content= "Hello 123456 World_This is a Regex Demo"
result = re.match("^He.*(\d+)\sWorld.*Demo$",content) 
print(result) #返回结果对象
print(result.group(1))#返回结果
<re.Match object; span=(0, 39), match='Hello 123456 World_This is a Regex Demo'>
6

非贪婪匹配

贪婪匹配会尽可能少的匹配字符,如下面例子,.* 会尽可能少的匹配任意字符,也就是后面的(\d+)代表一个或者多个字符。所以123456都被 (\d+) 匹配了,而.* 只匹配了前面的llo

  • .*?:非贪婪模式
import re

content= "Hello 123456 World_This is a Regex Demo"
result = re.match("^He.*?(\d+)\sWorld.*Demo$",content) 
print(result) #返回结果对象
print(result.group(1))#返回结果
<re.Match object; span=(0, 39), match='Hello 123456 World_This is a Regex Demo'>
123456

匹配模式

`flags 参数传入 re.S.表示任意字符,不指定时,不包括换行符。

import re

content= "Hello 123456 World_This \n is a Regex Demo"
result = re.match("^He.*?(\d+)\sWorld.*Demo$",content,re.S) 
print(result) #返回结果对象
print(result.group(1))#返回结果
<re.Match object; span=(0, 41), match='Hello 123456 World_This \n is a Regex Demo'>
123456

转义

假设目标字符串中有 特殊字符如 .$ 等,该怎么匹配呢,可以用转义符 \ 进行转义

import re

content= "price is $5.00"
result = re.match("^price is \$5\.00",content,re.S) 
print(result) #返回结果对象
print(result.group())#返回结果
<re.Match object; span=(0, 14), match='price is $5.00'>
price is $5.00

re.search

扫描整个字符串,找到第一个成功的匹配并返回

import re

content= "Extra setting  Hello domain I am 18 years old."
result = re.search("^.* (Hello.*.$)",content,re.S) 
print(result) #返回结果对象
print(result.group(1))#返回结果
<re.Match object; span=(0, 46), match='Extra setting  Hello domain I am 18 years old.'>
Hello domain I am 18 years old.

总结: 能用search就不用match

re.findall

搜索字符串以列表形式返回所有能够匹配的字符

re.sub

替换字符串中每一个能匹配的字符串后返回字符串,如下面把数字替换为空

import re

content= "Extra setting  Hello domain I am 18 years old."
content = re.sub("\d+","",content)
print(content) #返回结果对象
Extra setting  Hello domain I am  years old.

替换时包含原字符串

修改时需要用到匹配到的原字符,如下面例子 把数字替换为原来数字加 123456

import re

content= "Extra setting  Hello domain I am 18 years old."
content = re.sub("(\d+)",r"\1 123456",content)
print(content) #返回结果对象
Extra setting  Hello domain I am 18 123456 years old.

re.compile

将一个正则表达式编译成一个正则对象,以便于复用该匹配模式

import re

content= "Hello 123456 World_This is a Regex Demo"

pattern = re.compile("^He.*?(\d+)\sWorld.*Demo$")
result = re.match(pattern,content) 
print(result) #返回结果对象
print(result.group(1))#返回结果
<re.Match object; span=(0, 39), match='Hello 123456 World_This is a Regex Demo'>
123456

实战练习

获取豆瓣图书(https://book.douban.com)图片的信息

import re,requests

content = requests.get("https://book.douban.com").text
pattern = re.compile('<li.*?cover.*?href="(.*?)".*?title="(.*?)".*?',re.S)
results=re.findall(pattern,content)
print(results)
import re, requests

content = requests.get("https://book.douban.com").text
# print(content)
with open('book_html.html','wb') as f:
    f.write(content.encode("utf-8"))
    f.close()
pattern = re.compile('<li.*?cover.*?href="(.*?)" title="(.*?)">.*?author">(.*?)</div>.*?</li>', re.S)
results = re.findall(pattern, content)

for result in results:
    url,title,author=result
    author=re.sub('/&nbsp;','',author).strip().split("&nbsp;")
    print(url,title,author)
https://book.douban.com/subject/30187217/?icn=index-editionrecommend 宋徽宗 ['[美] 伊沛霞']
https://book.douban.com/subject/27191009/?icn=index-editionrecommend 往事与随想 ['[俄] 赫尔岑']
https://book.douban.com/subject/30289880/?icn=index-editionrecommend 生而不凡 ['[马来西亚]维申·拉克雅礼(Vishen Lakhiani)']
https://book.douban.com/subject/30288357/?icn=index-editionrecommend 用一朵花改变世界 ['石玉', '刘东炎']
https://book.douban.com/subject/30143251/?icn=index-editionrecommend 老后破产 ['日本NHK特别节目录制组']
https://book.douban.com/subject/30247619/?icn=index-latestbook-subject 坚果壳 ['[英] 伊恩·麦克尤恩']
https://book.douban.com/subject/30199456/?icn=index-latestbook-subject 执迷 ['(美)苏珊·福沃德博士', '(美)克雷格·巴克']
https://book.douban.com/subject/30245839/?icn=index-latestbook-subject 华龙之宫 ['[日] 上田早夕里']
https://book.douban.com/subject/30289362/?icn=index-latestbook-subject 明年更年轻:运动赋能篇 ['[美] 克里斯·克劳利', '亨利·洛奇']
https://book.douban.com/subject/30275106/?icn=index-latestbook-subject 银河边缘001:奇境 ['杨枫', '[美] 迈克·雷斯尼克 编', '[美]刘宇昆', '[美]杰克·威廉森', '美]罗伯特·西尔弗伯格', '[美]南希·克雷斯', '[美]汤姆·格伦瑟', '[美]凯济·约翰逊', '[美]格里高利·本福德', '付强', '梁清散', '李盆', '[澳大利亚]尼克·T. 陈', '[美]海蒂·鲁比·米勒', '[美]丹尼尔·F. 伽卢耶']
https://book.douban.com/subject/30272408/?icn=index-latestbook-subject 夏与西伯利亚 ['倪湛舸']
https://book.douban.com/subject/27622645/?icn=index-latestbook-subject 崖山 ['吕玻']
https://book.douban.com/subject/30246798/?icn=index-latestbook-subject 旅行手帐完全指南 ['[日] 奥野宣之']
https://book.douban.com/subject/30262577/?icn=index-latestbook-subject 天使之触 ['[英] 乔纳森·莫里斯']
https://book.douban.com/subject/30265800/?icn=index-latestbook-subject 平常的恶 ['[美] 朱迪丝·N.施克莱']
https://book.douban.com/subject/30281971/?icn=index-latestbook-subject 推理作家的信条 ['王稼骏']
https://book.douban.com/subject/30273572/?icn=index-latestbook-subject 识字的用途 ['[英] 理查德•霍加特']
https://book.douban.com/subject/30255671/?icn=index-latestbook-subject 碗 ['金宇澄']
https://book.douban.com/subject/30240081/?icn=index-latestbook-subject 印度佛教史 ['[日] 平川彰']
https://book.douban.com/subject/30237215/?icn=index-latestbook-subject 时间不存在 ['韩松', '[美] 刘宇昆', '罗伯特•西尔弗伯格', '[加拿大] 罗伯特·索耶', '加里•韦斯特福尔', '伊恩•沃森', '[美] 詹姆斯·冈恩', '宝树', '西奥多•赛德', '加里•K•沃尔夫', '克里斯多夫•普利斯特', '滕野', '万象峰年', '糖匪', '双翅目', '慕明', '任杰', '任雅琪', '保罗·琴凯德', '戴维·兰福德', '戴维·I·马森', '加里·库巴', '威廉·泰恩', '周留']
https://book.douban.com/subject/30240074/?icn=index-latestbook-subject 我每天只工作3小时 ['[日]押井守']
https://book.douban.com/subject/27127568/?icn=index-latestbook-subject 春天 ['阿乙']
https://book.douban.com/subject/28355841/?icn=index-latestbook-subject 四百击 ['[法]特吕弗']
https://book.douban.com/subject/30241252/?icn=index-latestbook-subject 弗兰肯斯坦在巴格达 ['[伊拉克] 艾哈迈德·萨达维']
https://book.douban.com/subject/27911231/?icn=index-latestbook-subject 万物并作 ['[美] 濮德培 (Peter C. Perdue)']
https://book.douban.com/subject/30282245/?icn=index-latestbook-subject 盂兰变 ['孟晖', '燕王WF']
https://book.douban.com/subject/30300327/?icn=index-latestbook-subject 料理图鉴 ['[日]越智登代子 著 / 平野惠理子 绘']
https://book.douban.com/subject/27605279/?icn=index-latestbook-subject 花街往事 ['路内']
https://book.douban.com/subject/30289118/?icn=index-latestbook-subject 未完的明治维新 ['[日]坂野润治']
https://book.douban.com/subject/30294068/?icn=index-latestbook-subject 总觉得有哪里不错 ['王XX']
https://book.douban.com/subject/30254388/?icn=index-latestbook-subject 两个世界的战争 ['[美]安东尼·帕戈登(Anthony Pagden)']
https://book.douban.com/subject/27601590/?icn=index-latestbook-subject 姜饼人 ['[爱尔兰] J. P. 唐利维']
https://book.douban.com/subject/30186003/?icn=index-latestbook-subject 左道 ['[美]万志英(Richard von Glahn)']
https://book.douban.com/subject/28356342/?icn=index-latestbook-subject 异类婚姻谭 ['[日]本谷有希子']
https://book.douban.com/subject/30259150/?icn=index-latestbook-subject 失明的摄影师 ['[英] 朱利安·罗森斯坦', '[英] 坎迪亚·麦克威廉', '[英] 梅尔·古丁 编著']
https://book.douban.com/subject/26952667/?icn=index-latestbook-subject 隐剑孤影抄 ['[日] 藤泽周平']
https://book.douban.com/subject/30276254/?icn=index-latestbook-subject 正午6 ['正午故事']
https://book.douban.com/subject/27046904/?icn=index-latestbook-subject 胡林的子女 ['[英] J·R·R·托尔金']
https://book.douban.com/subject/30237192/?icn=index-latestbook-subject 莫迪里阿尼 ['[英] 道格拉斯·霍尔', 'Douglas Hall']
https://book.douban.com/subject/30243868/?icn=index-latestbook-subject 犹太警察工会 ['[美] 迈克尔·夏邦']
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值