正则表达式

什么是正则表达式?

定义:正则表达式是对字符操作的一种逻辑公式,就是用事先定义好的一些特定的字符、及这些特定字符的组合,组成一个“规则字符串”,这个“规则字符串” 用来表达对字符的一种过滤逻辑。
非Python独有,re模块实现

样例展示

推荐网址 [http://tool.oschina.net/regex/#]在线正则表达式测试,并且有相关提取规则可以直接使用。

规则讲解

模式 描述
\w 匹配字母数字及下划线
\W 匹配非字母数字下划线
\s 匹配任意空白字符,等价于 [\t\n\r\f].
\S 匹配任意非空字符
\d 匹配任意数字,等价于 [0-9]
\D 匹配任意非数字
\A 匹配字符串开始
\Z 匹配字符串结束,如果是存在换行,只匹配到换行前的结束字符串
\z 匹配字符串结束
\G 匹配最后匹配完成的位置
\n 匹配一个换行符
\t 匹配一个制表符
^ 匹配字符串的开头
$ 匹配字符串的末尾。
. 匹配任意字符,除了换行符,当re.DOTALL标记被指定时,则可以匹配包括换行符的任意字符。
[…] 用来表示一组字符,单独列出:[amk] 匹配 ‘a’,’m’或’k’
[^…] 不在[]中的字符:[^abc] 匹配除了a,b,c之外的字符。
* 匹配0个或多个的表达式。
+ 匹配1个或多个的表达式。
? 匹配0个或1个由前面的正则表达式定义的片段,非贪婪方式
{n} 精确匹配n个前面表达式。
{n, m} 匹配 n 到 m 次由前面的正则表达式定义的片段,贪婪方式
a|b 匹配a或b
( ) 匹配括号内的表达式,也表示一个组

re.match()

re.match 尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match()就返回none。

re.match(pattern, string, flags=0)

import re
content = 'Hello 123 4567 World_This is a Regex Demo'
print(len(content))
result = re.match('^Hello\s\d\d\d\s\d{4}\s\w{10}.*Demo$', content)
print(result)
print(result.group())
print(result.span())

泛匹配:

import recontent = 'Hello 123 4567 World_This is a Regex Demo'
result = re.match('^Hello.*Demo$', content)
print(result)
print(result.group())
print(result.span())

.* 可以匹配多个任意字符

匹配目标:

import recontent = 'Hello 1234567 World_This is a Regex Demo'
result = re.match('^Hello\s(\d+)\sWorld.*Demo$', content)
print(result)
print(result.group(1))
print(result.span())

贪婪匹配

import recontent = 'Hello 1234567 World_This is a Regex Demo'
result = re.match('^He.*(\d+).*Demo$', content)
print(result)
print(result.group(1))

结果为 7
.* 可以匹配尽可能多的字符串。

非贪婪模式

import recontent = 'Hello 1234567 World_This is a Regex Demo'
result = re.match('^He.*?(\d+).*Demo$', content)
print(result)
print(result.group(1))

.*?可以匹配一个字符即可。

匹配模式

import recontent = '''Hello 1234567 World_This
is a Regex Demo
'''
result = re.match('^He.*?(\d+).*?Demo$', content, re.S)
print(result.group(1))

注意 . 是不能匹配换行符的。所以如果要匹配换行符加上参数re.S。

转义

import recontent = 'price is $5.00'
result = re.match('price is $5.00', content)
print(result)

结果:
None

import recontent = 'price is $5.00'
result = re.match('price is \$5\.00', content)
print(result)

价格转移符号,就可以匹配了。

总结:尽量使用泛匹配,使用括号得到匹配目标,尽量使用非贪婪模式,有换行符就用re.S。这里写代码片

实战演练

import rehtml = '''<div id="songs-list"><h2 class="title">经典老歌</h2><p class="introduction">经典老歌列表</p><ul id="list" class="list-group"><li data-view="2">一路上有你</li><li data-view="7"><a href="/2.mp3" singer="任贤齐">沧海一声笑</a></li><li data-view="4" class="active"><a href="/3.mp3" singer="齐秦">往事随风</a></li><li data-view="6"><a href="/4.mp3" singer="beyond">光辉岁月</a></li><li data-view="5"><a href="/5.mp3" singer="陈慧琳">记事本</a></li><li data-view="5"><a href="/6.mp3" singer="邓丽君"><i class="fa fa-user"></i>但愿人长久</a></li></ul>
</div>'''
result = re.search('<li.*?active.*?singer="(.*?)">(.*?)</a>', html, re.S)
if result:print(result.group(1), result.group(2))

匹配代码:

html = '''<div id="songs-list"><h2 class="title">经典老歌</h2><p class="introduction">经典老歌列表</p><ul id="list" class="list-group"><li data-view="2">一路上有你</li><li data-view="7"><a href="/2.mp3" singer="任贤齐">沧海一声笑</a></li><li data-view="4" class="active"><a href="/3.mp3" singer="齐秦">往事随风</a></li><li data-view="6"><a href="/4.mp3" singer="beyond">光辉岁月</a></li><li data-view="5"><a href="/5.mp3" singer="陈慧琳">记事本</a></li><li data-view="5"><a href="/6.mp3" singer="邓丽君">但愿人长久</a></li></ul>
</div>'''
result = re.search('<li.*?singer="(.*?)">(.*?)</a>', html, re.S)
if result:print(result.group(1), result.group(2))

2.

import rehtml = '''<div id="songs-list"><h2 class="title">经典老歌</h2><p class="introduction">经典老歌列表</p><ul id="list" class="list-group"><li data-view="2">一路上有你</li><li data-view="7"><a href="/2.mp3" singer="任贤齐">沧海一声笑</a></li><li data-view="4" class="active"><a href="/3.mp3" singer="齐秦">往事随风</a></li><li data-view="6"><a href="/4.mp3" singer="beyond">光辉岁月</a></li><li data-view="5"><a href="/5.mp3" singer="陈慧琳">记事本</a></li><li data-view="5"><a href="/6.mp3" singer="邓丽君">但愿人长久</a></li></ul>
</div>'''
result = re.search('<li.*?singer="(.*?)">(.*?)</a>', html)
if result:print(result.group(1), result.group(2))

结果:beyond 光辉岁月

re.findall()

import rehtml = '''<div id="songs-list"><h2 class="title">经典老歌</h2><p class="introduction">经典老歌列表</p><ul id="list" class="list-group"><li data-view="2">一路上有你</li><li data-view="7"><a href="/2.mp3" singer="任贤齐">沧海一声笑</a></li><li data-view="4" class="active"><a href="/3.mp3" singer="齐秦">往事随风</a></li><li data-view="6"><a href="/4.mp3" singer="beyond">光辉岁月</a></li><li data-view="5"><a href="/5.mp3" singer="陈慧琳">记事本</a></li><li data-view="5"><a href="/6.mp3" singer="邓丽君">但愿人长久</a></li></ul>
</div>'''
results = re.findall('<li.*?href="(.*?)".*?singer="(.*?)">(.*?)</a>', html, re.S)
print(results)
print(type(results))
for result in results:print(result)print(result[0], result[1], result[2])

结果:

[('/2.mp3', '任贤齐', '沧海一声笑'), ('/3.mp3', '齐秦', '往事随风'), ('/4.mp3', 'beyond', '光辉岁月'), ('/5.mp3', '陈慧琳', '记事本'), ('/6.mp3', '邓丽君', '但愿人长久')]
<class 'list'>
('/2.mp3', '任贤齐', '沧海一声笑')
/2.mp3 任贤齐 沧海一声笑
('/3.mp3', '齐秦', '往事随风')
/3.mp3 齐秦 往事随风
('/4.mp3', 'beyond', '光辉岁月')
/4.mp3 beyond 光辉岁月
('/5.mp3', '陈慧琳', '记事本')
/5.mp3 陈慧琳 记事本
('/6.mp3', '邓丽君', '但愿人长久')
/6.mp3 邓丽君 但愿人长久

re.sub()

替换字符串中每一个匹配的子串后返回替换后的字符串。
1.


content = 'Extra stings Hello 1234567 World_This is a Regex Demo Extra stings'
content = re.sub('\d+', '', content)
print(content)

结果 Extra stings Hello World_This is a Regex Demo Extra stings

2.

import recontent = 'Extra stings Hello 1234567 World_This is a Regex Demo Extra stings'
content = re.sub('\d+', 'Replacement', content)
print(content)

结果:Extra stings Hello Replacement World_This is a Regex Demo Extra stings

3.

import recontent = 'Extra stings Hello 1234567 World_This is a Regex Demo Extra stings'
content = re.sub('(\d+)', r'\1 8910', content)
print(content)

结果:

Extra stings Hello 1234567 8910 World_This is a Regex Demo Extra stings

re.sub()运用实例

import rehtml = '''<div id="songs-list"><h2 class="title">经典老歌</h2><p class="introduction">经典老歌列表</p><ul id="list" class="list-group"><li data-view="2">一路上有你</li><li data-view="7"><a href="/2.mp3" singer="任贤齐">沧海一声笑</a></li><li data-view="4" class="active"><a href="/3.mp3" singer="齐秦">往事随风</a></li><li data-view="6"><a href="/4.mp3" singer="beyond">光辉岁月</a></li><li data-view="5"><a href="/5.mp3" singer="陈慧琳">记事本</a></li><li data-view="5"><a href="/6.mp3" singer="邓丽君">但愿人长久</a></li></ul>
</div>'''
html = re.sub('<a.*?>|</a>', '', html)
print(html)
results = re.findall('<li.*?>(.*?)</li>', html, re.S)
print(results)
for result in results:print(result.strip())

输出结果为:

<div id="songs-list"><h2 class="title">经典老歌</h2><p class="introduction">经典老歌列表</p><ul id="list" class="list-group"><li data-view="2">一路上有你</li><li data-view="7">沧海一声笑</li><li data-view="4" class="active">往事随风</li><li data-view="6">光辉岁月</li><li data-view="5">记事本</li><li data-view="5">但愿人长久</li></ul>
</div>
['一路上有你', '\n            沧海一声笑\n        ', '\n            往事随风\n        ', '光辉岁月', '记事本', '\n            但愿人长久\n        ']
一路上有你
沧海一声笑
往事随风
光辉岁月
记事本
但愿人长久

豆瓣实战演练


import requests
import re
content = requests.get('https://book.douban.com/').text
pattern = re.compile('<li.*?cover.*?href="(.*?)".*?title="(.*?)".*?more-meta.*?author">(.*?)</span>.*?year">(.*?)</span>.*?</li>', re.S)
results = re.findall(pattern, content)
for result in results:url, name, author, date = resultauthor = re.sub('\s', '', author)date = re.sub('\s', '', date)print(url, name, author, date)

结果如下:

https://book.douban.com/subject/27132522/?icn=index-editionrecommend 唐译子不语 【清】袁枚著
https://book.douban.com/subject/27123918/?icn=index-editionrecommend 使徒 冰河 2017-7-1
https://book.douban.com/subject/27102701/?icn=index-editionrecommend 另一种选择 [美]谢丽尔•桑德伯格 2017-8
https://book.douban.com/subject/27077702/?icn=index-editionrecommend 故宫院长说故宫 李文儒 2017-8-1
https://book.douban.com/subject/27092880/?icn=index-editionrecommend 这本书能让你睡得好 [美]肖恩·史蒂文森(ShawnStevenson) 2017-8-1
https://book.douban.com/subject/27077339/?icn=index-latestbook-subject 德里纳河上的桥 [塞尔维亚]伊沃·安德里奇 2017-8
https://book.douban.com/subject/27081056/?icn=index-latestbook-subject 世界历史上的蒙古征服 [美]梅天穆 2017-10
https://book.douban.com/subject/27064053/?icn=index-latestbook-subject 一月物语 [日]平野启一郎 2017-8-1
https://book.douban.com/subject/27102845/?icn=index-latestbook-subject 最寒冷的冬天 [美]大卫·哈伯斯塔姆 2017-8-1
https://book.douban.com/subject/27103712/?icn=index-latestbook-subject 雨中杀手 [美]雷蒙德·钱德勒 2017-9
https://book.douban.com/subject/27091561/?icn=index-latestbook-subject 关羽 渡边义浩 2017-9
https://book.douban.com/subject/27115747/?icn=index-latestbook-subject 两只空气同时落球 陈卫 2017-9-1
https://book.douban.com/subject/26688765/?icn=index-latestbook-subject 论巴赫 [德]阿尔伯特·施韦泽 2017-9-1
https://book.douban.com/subject/27118271/?icn=index-latestbook-subject 今夜宜有彩虹 陆烨华 2017-10
https://book.douban.com/subject/27098403/?icn=index-latestbook-subject 这幅画还可以看这里 [日]宫下规久朗 2017-8
https://book.douban.com/subject/27104274/?icn=index-latestbook-subject 三个彩色故事 [巴西]若热·亚马多 2017-9
https://book.douban.com/subject/27113372/?icn=index-latestbook-subject 父亲的失乐园 [美]阿里埃勒·萨巴尔 2017-9
https://book.douban.com/subject/27108544/?icn=index-latestbook-subject 这里 [美]理查德·麦奎尔 2017-10
https://book.douban.com/subject/27118642/?icn=index-latestbook-subject 和纸之美 [日]柳宗悦 2017-9
https://book.douban.com/subject/26939977/?icn=index-latestbook-subject 事故 [阿尔巴尼亚]伊斯梅尔·卡达莱 2017-8
https://book.douban.com/subject/27045312/?icn=index-latestbook-subject 腹地的构建 [美]彭慕兰 2017-8
https://book.douban.com/subject/27124852/?icn=index-latestbook-subject 我循着火光而来 张悦然 2017-10
https://book.douban.com/subject/27089521/?icn=index-latestbook-subject 中东死生门 周轶君 2017-8-1
https://book.douban.com/subject/27104531/?icn=index-latestbook-subject 布园重访 [英]伊夫林·沃 2017-9
https://book.douban.com/subject/27093323/?icn=index-latestbook-subject 百年战争简史 [英]德斯蒙德·苏厄德 2017-9
https://book.douban.com/subject/27119165/?icn=index-latestbook-subject 春天大概需要你 暗号 2017-8
https://book.douban.com/subject/27001191/?icn=index-latestbook-subject 生逢其时 [英]戴维·洛奇 2017-9
https://book.douban.com/subject/27098887/?icn=index-latestbook-subject 沙丘2:沙丘救世主 [美]弗兰克·赫伯特 2017-8
https://book.douban.com/subject/27127066/?icn=index-latestbook-subject 知中·了不起的宋版书 罗威尔 / 主编 2017-8
https://book.douban.com/subject/27116030/?icn=index-latestbook-subject A致X [英]约翰·伯格 2017-8-1
https://book.douban.com/subject/27126207/?icn=index-latestbook-subject 蔬菜教室 [日]内田悟 2017-10
https://book.douban.com/subject/27079479/?icn=index-latestbook-subject 南方高速 [阿根廷]胡利奥·科塔萨尔 2017-10
https://book.douban.com/subject/27120282/?icn=index-latestbook-subject 寻路阿富汗 [英]罗瑞·斯图尔特 2017-8
https://book.douban.com/subject/26689052/?icn=index-latestbook-subject 狗样的春天 [法]帕特里克·莫迪亚诺 2017-8
https://book.douban.com/subject/27134137/?icn=index-latestbook-subject 白夜追凶 指纹 2017-9-1
https://book.douban.com/subject/26989965/?icn=index-latestbook-subject 罂粟与记忆 [德]保罗·策兰(PaulCelan) 2017-8
https://book.douban.com/subject/27046176/?icn=index-latestbook-subject 东镇女巫 [美]约翰·厄普代克 2017-8
https://book.douban.com/subject/27112626/?icn=index-latestbook-subject 理解戈达尔 [法]米歇尔·玛利 2017-9-1
https://book.douban.com/subject/27101592/?icn=index-latestbook-subject 我认识了一个索马里海盗 邓安庆 2017-9
https://book.douban.com/subject/27036755/?icn=index-latestbook-subject 远方的陌生人 [美]詹姆斯·弗农 2017-7
https://www.douban.com/note/635568967/ 双峰:神秘史 [美]马克·弗罗斯特 2017-7-16
https://read.douban.com/ebook/16269557/?dcs=book-hot&dcm=douban&dct=read-subject 古董局中局·大全集(共4册) 马伯庸 2015-12
https://read.douban.com/ebook/2523017/?dcs=book-hot&dcm=douban&dct=read-subject 毛姆短篇小说精选集 (英)威廉·萨默塞特·毛姆 2012-11
https://read.douban.com/ebook/39766537/?dcs=book-hot&dcm=douban&dct=read-subject 我循着火光而来 张悦然 2017-10
https://read.douban.com/ebook/11593161/?dcs=book-hot&dcm=douban&dct=read-subject 目送 龙应台 2014-1
https://read.douban.com/ebook/39961798/?dcs=book-hot&dcm=douban&dct=read-subject 偷窥者 秦明 2017-7
https://read.douban.com/ebook/5812677/?dcs=book-hot&dcm=douban&dct=read-subject 遇见孩子,遇见更好的自己 【美】赛西•高夫/戴维•托马斯/梅丽莎•切瓦特桑 2014-10-1
https://read.douban.com/ebook/39805161/?dcs=book-hot&dcm=douban&dct=read-subject 成功与运气 罗伯特·弗兰克 2017-9
https://read.douban.com/ebook/40071710/?dcs=book-hot&dcm=douban&dct=read-subject 不然你搬去火星啊 [日]伊坂幸太郎 2016-8
https://read.douban.com/ebook/405202/?dcs=book-hot&dcm=douban&dct=read-subject 嫌疑人X的献身 [日]东野圭吾 2008-9

四. 正则表达式的使用相关推荐

  1. LAMP兄弟连原创视频教程(PHP笔记四--正则表达式,文件,目录操作)

    8.1 正则表达式的功能介绍 与正则表达式:是用描述字符排列模式一种语法规则 作用:字符串的模式分割.匹配.查找.替换 正规字符:abcd 13456 特殊字符:() ? ^ $ 原子:(普通字符,如 ...

  2. javascript知识点整理(四) 正则表达式

    正则表达式 用于定义一些字符串的规则,计算机可以根据正则表达式,来检查字符串是否符合规则,获取字符串中符合规则的内容提取出来. 创建正则表达式对象 语法: var reg=new RegExp(&qu ...

  3. perl基本语法四-正则表达式

    文章目录 1.模式匹配 2.反向引用 3.常用符号 4.锚位 5.绑定操作符~ 6.模式串中的内插 7.捕获变量 1.捕获变量() 2.只分组不捕获(?:) 3.捕获变量命名(?<>) 4 ...

  4. Python学习日记(十四) 正则表达式和re模块

    正则表达式: 它是字符串的一种匹配模式,用来处理字符串,可以极大地减轻处理一些复杂字符串的代码量 字符组:它是在同一位置可能出现的各种字符组成了一个字符组,用[]表示,但是它的结果只能是一个数字或者一 ...

  5. python正则表达式思考_PYTHON 爬虫笔记四:正则表达式基础用法

    [('https://book.douban.com/subject/30274766/?icn=index-editionrecommend', '潦草', '\n 贾行家\n', '\n 2018 ...

  6. [Python从零到壹] 四.网络爬虫之入门基础及正则表达式抓取博客案例

    欢迎大家来到"Python从零到壹",在这里我将分享约200篇Python系列文章,带大家一起去学习和玩耍,看看Python这个有趣的世界.所有文章都将结合案例.代码和作者的经验讲 ...

  7. c#使用正则表达式获取TR中的多个TD_[Python从零到壹] 四.网络爬虫之入门基础及正则表达式抓取博客案例...

    首先祝大家中秋节和国庆节快乐,欢迎大家来到"Python从零到壹",在这里我将分享约200篇Python系列文章,带大家一起去学习和玩耍,看看Python这个有趣的世界.所有文章都 ...

  8. python爬虫提取人名_python爬虫—爬取英文名以及正则表达式的介绍

    python爬虫-爬取英文名以及正则表达式的介绍 爬取英文名: 一. 爬虫模块详细设计 (1)整体思路 对于本次爬取英文名数据的爬虫实现,我的思路是先将A-Z所有英文名的连接爬取出来,保存在一个csv ...

  9. linux系统结构,文件寻址,文件管理编辑,正则表达式

    一.linux系统结构 linux是一个倒树结构,linux中所有的东西都是文件,这些文件都在系统顶级目录"/" /就是根目录 /目录以下为二级目录这些目录都是系统装机时系统自动建 ...

最新文章

  1. P1338 末日的传说
  2. android 启动服务权限,android – 当我尝试启动服务时权限被拒绝
  3. mit risc-v 资料
  4. day23 01 类的命名空间
  5. Actor-ES框架:Ray-Handler之CoreHandler编写
  6. 杭电oj2047-2049、2051-2053、2056、2058
  7. [Robot Framework] 怎么做数学运算?
  8. python地图标注_Python 给定的经纬度标注在地图上的实现方法
  9. [CF706D]Vasiliy's Multiset(异或字典树)
  10. AD16报错some nets were not able matched网络不能匹配
  11. Unity 使用tiledmap解析地图
  12. 推荐几个e书下载地址
  13. 纯css按钮代码,纯CSS实现3D按钮效果实例代码
  14. bittorrent下载_面向初学者的BitTorrent:如何开始下载Torrent
  15. PAT 乙级1068 万绿丛中一点红(20 分)
  16. 数据分析-美国小孩英文名分析-可视化(含代码)
  17. 如何查看Android API文档
  18. 记我一次成功的入侵学校网站服务器的黑客行动
  19. RulersGuides.js – 网站中实现 Photoshop 标尺效果
  20. 视频显示输出接口总结

热门文章

  1. STM32 HAL库之USB
  2. 消息中间件ActiveMQ 4: 传输协议
  3. windows 根据端口杀进程 部署jar包 批处理脚本
  4. CompletableFuture的正常,异常,timeout和cancel
  5. 坑人无数的俩货:半包和粘包
  6. 关于KEIL SCT文件重写
  7. 基于51单片机的温控系统
  8. java 电子围栏_怎么画电子围栏,并进行电子围栏进出判断?
  9. Django项目之美多商城遇到的问题记录与解决(一)
  10. ADO数据库连接中的Integrated Security和Persist Security Info参数的作用