正则表达式
正则表达式
常见匹配模式
| 模式 | 描述 |
|---|---|
| \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)
最常规的匹配
In [1]: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())
41
<_sre.SRE_Match object; span=(0, 41), match='Hello 123 4567 World_This is a Regex Demo'>
Hello 123 4567 World_This is a Regex Demo
(0, 41)
泛匹配
In [18]:import re
content = 'Hello 123 4567 World_This is a Regex Demo'
result = re.match('^Hello.*Demo$', content)
print(result)
print(result.group())
print(result.span())
<_sre.SRE_Match object; span=(0, 41), match='Hello 123 4567 World_This is a Regex Demo'>
Hello 123 4567 World_This is a Regex Demo
(0, 41)
匹配目标
In [20]:import re
content = '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())
<_sre.SRE_Match object; span=(0, 40), match='Hello 1234567 World_This is a Regex Demo'>
1234567
(0, 40)
贪婪匹配
In [21]:import re
content = 'Hello 1234567 World_This is a Regex Demo'
result = re.match('^He.*(\d+).*Demo$', content)
print(result)
print(result.group(1))
<_sre.SRE_Match object; span=(0, 40), match='Hello 1234567 World_This is a Regex Demo'>
7
非贪婪匹配
In [22]:import re
content = 'Hello 1234567 World_This is a Regex Demo'
result = re.match('^He.*?(\d+).*Demo$', content)
print(result)
print(result.group(1))
<_sre.SRE_Match object; span=(0, 40), match='Hello 1234567 World_This is a Regex Demo'>
1234567
匹配模式
In [26]:import re
content = '''Hello 1234567 World_This
is a Regex Demo
'''
result = re.match('^He.*?(\d+).*?Demo$', content, re.S)
print(result.group(1))
1234567
转义
In [28]:import re
content = 'price is $5.00'
result = re.match('price is $5.00', content)
print(result)
None
In [31]:
import re
content = 'price is $5.00'
result = re.match('price is \$5\.00', content)
print(result)
<_sre.SRE_Match object; span=(0, 14), match='price is $5.00'>
总结:尽量使用泛匹配、使用括号得到匹配目标、尽量使用非贪婪模式、有换行符就用re.S 但是match方法会从第一个字母进行匹配,如果第一个字母没有会出现None的情况
re.search
re.search 扫描整个字符串并返回第一个成功的匹配。
In [32]:import re
content = 'Extra stings Hello 1234567 World_This is a Regex Demo Extra stings'
result = re.match('Hello.*?(\d+).*?Demo', content)
print(result)
None
In [35]:
import re
content = 'Extra stings Hello 1234567 World_This is a Regex Demo Extra stings'
result = re.search('Hello.*?(\d+).*?Demo', content)
print(result)
print(result.group(1))
<_sre.SRE_Match object; span=(13, 53), match='Hello 1234567 World_This is a Regex Demo'>
1234567
总结:为匹配方便,能用search就不用match
匹配演练
In [36]:import re
html = ''''''
result = re.search('(.*?)', html, re.S)
if result:
print(result.group(1), result.group(2))
齐秦 往事随风
In [37]:
import re
html = ''''''
result = re.search('(.*?)', html, re.S)
if result:
print(result.group(1), result.group(2))
任贤齐 沧海一声笑
In [40]:
import re
html = ''''''
result = re.search('(.*?)', html)
if result:
print(result.group(1), result.group(2))
beyond 光辉岁月
re.findall
搜索字符串,以列表形式返回全部能匹配的子串。 re.search是搜寻一个结果的;findall是搜寻多个结果的
In [44]:import re
html = ''''''
results = re.findall('(.*?)', 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', '邓丽君', '但愿人长久')]
('/2.mp3', '任贤齐', '沧海一声笑')
/2.mp3 任贤齐 沧海一声笑
('/3.mp3', '齐秦', '往事随风')
/3.mp3 齐秦 往事随风
('/4.mp3', 'beyond', '光辉岁月')
/4.mp3 beyond 光辉岁月
('/5.mp3', '陈慧琳', '记事本')
/5.mp3 陈慧琳 记事本
('/6.mp3', '邓丽君', '但愿人长久')
/6.mp3 邓丽君 但愿人长久
In [46]:
import re
html = ''''''
results = re.findall('\s*?()?(\w+)()?\s*?', html, re.S)
print(results)
for result in results:
print(result[1])
[('', '一路上有你', ''), ('', '沧海一声笑', ''), ('', '往事随风', ''), ('', '光辉岁月', ''), ('', '记事本', ''), ('', '但愿人长久', '')]
一路上有你
沧海一声笑
往事随风
光辉岁月
记事本
但愿人长久
re.sub
替换字符串中每一个匹配的子串后返回替换后的字符串。
In [47]:import re
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
In [48]:
import re
content = '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
In [51]:
import re
content = '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
In [ ]:
import re
html = ''''''
In [54]:
import re
html = ''''''
html = re.sub('|', '', html)
print(html)
results = re.findall('(.*?)', html, re.S)
print(results)
for result in results:
print(result.strip())
经典老歌
经典老歌列表
- 一路上有你
-
沧海一声笑
-
往事随风
- 光辉岁月
- 记事本
-
但愿人长久
['一路上有你', '\n 沧海一声笑\n ', '\n 往事随风\n ', '光辉岁月', '记事本', '\n 但愿人长久\n ']
一路上有你
沧海一声笑
往事随风
光辉岁月
记事本
但愿人长久
re.compile
将正则字符串编译成正则表达式对象
In [ ]:将一个正则表达式串编译成正则对象,以便于复用该匹配模式
In [57]:
import re
content = '''Hello 1234567 World_This
is a Regex Demo'''
pattern = re.compile('Hello.*Demo', re.S)
result = re.match(pattern, content)
#result = re.match('Hello.*Demo', content, re.S)
print(result)
<_sre.SRE_Match object; span=(0, 40), match='Hello 1234567 World_This\nis a Regex Demo'>
实战练习
In [1]:import requests
import re
url='https://book.douban.com/'
header={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36'}
content=requests.get(url,headers=header).text
# content = requests.get('https://book.douban.com/').text
pattern = re.compile('(.*?).*?year">(.*?).*?', re.S)
results = re.findall(pattern, content)
for result in results:
url, name, author, date = result
author = re.sub('\s', '', author)
date = re.sub('\s', '', date)
print(url, name, author, date)
https://book.douban.com/subject/35136072/?icn=index-latestbook-subject 其后 それから 赖香吟 2020-9
https://book.douban.com/subject/35080708/?icn=index-latestbook-subject 我是谁,或什么 [美]侯世达 / [美]丹尼尔·丹尼特 2020-7
https://book.douban.com/subject/35083075/?icn=index-latestbook-subject 我这样的机器 [英]伊恩·麦克尤恩 2020-7
https://book.douban.com/subject/35134022/?icn=index-latestbook-subject 岂不怀归 田丰 / 林凯玄 2020-8
https://book.douban.com/subject/35115625/?icn=index-latestbook-subject 文青之死 赖香吟 2020-9
https://book.douban.com/subject/35154591/?icn=index-latestbook-subject 刑法学讲义 罗翔 2020-8-1
https://book.douban.com/subject/35125691/?icn=index-latestbook-subject 刚刚 刘按 2020-7-15
https://book.douban.com/subject/35140008/?icn=index-latestbook-subject 阅读是一座随身携带的避难所 [英]威廉·萨默塞特·毛姆 2020-7
https://book.douban.com/subject/35081845/?icn=index-latestbook-subject 证言 [加拿大]玛格丽特·阿特伍德 2020-7
https://book.douban.com/subject/35099263/?icn=index-latestbook-subject 资本主义的未来 [英]保罗·科利尔 2020-7
https://book.douban.com/subject/34949694/?icn=index-latestbook-subject 往复书简 [日]坂元裕二 2020-8
https://book.douban.com/subject/35101638/?icn=index-latestbook-subject 别只叫我女孩 [美]马伊姆·拜力克 2020-7
https://book.douban.com/subject/35080696/?icn=index-latestbook-subject 花园中的处子 [英]A·S·拜厄特 2020-7
https://book.douban.com/subject/35013931/?icn=index-latestbook-subject 华夏边缘 王明珂 2020-7
https://book.douban.com/subject/34858994/?icn=index-latestbook-subject 树民 [美]安妮·普鲁 2020-7
https://book.douban.com/subject/34990157/?icn=index-latestbook-subject 女佣的故事 [美]斯蒂芬妮?兰德(StephanieLand) 2020-6
https://book.douban.com/subject/35063947/?icn=index-latestbook-subject 满是空虚之物 [日]阿伏伽德六 2020-8
https://book.douban.com/subject/34870283/?icn=index-latestbook-subject 老年实用手册 宗泽亚 2020-7
https://book.douban.com/subject/35080704/?icn=index-latestbook-subject 杀鬼 甘耀明 2020-8-1
https://book.douban.com/subject/35061771/?icn=index-latestbook-subject 恶魔之城 [英]保罗·法兰奇 2020-7
https://book.douban.com/subject/35081921/?icn=index-latestbook-subject 正常人 [爱尔兰]萨莉·鲁尼 2020-7
https://book.douban.com/subject/35094702/?icn=index-latestbook-subject 黑色电影 [美]詹姆斯·纳雷摩尔 2020-8
https://book.douban.com/subject/35141940/?icn=index-latestbook-subject 晚熟的人 莫言 2020-8-1
https://book.douban.com/subject/35133888/?icn=index-latestbook-subject 如何停止不开心 [美]安德烈娅·欧文 / AndreaOwen 2020-8
https://book.douban.com/subject/35149238/?icn=index-latestbook-subject 神话 [英]斯蒂芬·弗莱(StephenFry) 2020-8-1
https://book.douban.com/subject/35059450/?icn=index-latestbook-subject 末日松茸 罗安清 2020-7
https://book.douban.com/subject/30159799/?icn=index-latestbook-subject 完美伴侣 [英]艾丽丝·默多克 2020-7
https://book.douban.com/subject/34902755/?icn=index-latestbook-subject 最后的皇族 [美]罗友枝 2020-8
https://book.douban.com/subject/35097123/?icn=index-latestbook-subject 马查多·德·阿西斯小说集 [巴西]马查多·德·阿西斯 2020-7
https://book.douban.com/subject/35062748/?icn=index-latestbook-subject 北欧神话 茅盾 2020-7
https://book.douban.com/subject/35097096/?icn=index-latestbook-subject 我的奋斗 4 [挪威]卡尔·奥韦·克瑙斯高 2020-7
https://book.douban.com/subject/35075145/?icn=index-latestbook-subject 神话全书 [西班牙]阿图罗·马塞洛·帕斯夸尔 / [西班牙]泰奥·戈麦斯 2020-8
https://book.douban.com/subject/35085896/?icn=index-latestbook-subject 我的乔治亚 西西 2020-7
https://book.douban.com/subject/35063742/?icn=index-latestbook-subject 托尔斯泰最后的日记 [俄]列夫·托尔斯泰 2020-7
https://book.douban.com/subject/35090798/?icn=index-latestbook-subject 带我回家 【加】乔安娜·古德曼 2020-7
https://book.douban.com/subject/35077962/?icn=index-latestbook-subject 许倬云说美国 许倬云 2020-7
https://book.douban.com/subject/35069474/?icn=index-latestbook-subject 性本恶 [美]托马斯·品钦 2020-7
https://book.douban.com/subject/35093999/?icn=index-latestbook-subject 知晓我姓名 [美]香奈儿·米勒 2020-8
https://book.douban.com/subject/35100261/?icn=index-latestbook-subject 枉死城事件 时晨 2020-7
https://book.douban.com/subject/34449349/?icn=index-latestbook-subject 名作家和他们的衣橱 [英]特莉·纽曼 2020-7
In [2]:
import requests
response=requests.get('https://movie.douban.com/').text
print(response)
In [ ]: