re模块
一:什么是正则?
正则就是用一些具有特殊含义的符号组合到一起(称为正则表达式)来描述字符或者字符串的方法。或者说:正则就是用来描述一类事物的规则。(在Python中)它内嵌在Python中,并通过 re 模块实现。正则表达式模式被编译成一系列的字节码,然后由用 C 编写的匹配引擎执行。
二:常用匹配模式(元字符)
补充:\b 匹配一个特殊字符边界,比如空格,&,#等
# =================================匹配模式=================================
# 正则匹配
import re
# \w 与 \W
print(re.findall('\w','hello long 123')) # ['h', 'e', 'l', 'l', 'o', 'l', 'o', 'n', 'g', '1', '2', '3']
print(re.findall('\W','hello long 123')) # [' ', ' ']
# \s 与 \S
print(re.findall('\s','hello long 123')) # [' ', ' ']
print(re.findall('\S','hello long 123')) # ['h', 'e', 'l', 'l', 'o', 'l', 'o', 'n', 'g', '1', '2', '3']
#\n \t都是空,都可以被\s匹配
print(re.findall('\s','hello \n long \t 123')) #[' ', '\n', ' ', ' ', '\t', ' ']
#\n与\t
print(re.findall(r'\n','hello long \n123')) #['\n']
print(re.findall(r'\t','hello long\t123')) #['\t']
#\d与\D
print(re.findall('\d','hello long 123')) # ['1', '2', '3']
print(re.findall('\D','hello long 123')) # ['h', 'e', 'l', 'l', 'o', ' ', 'l', 'o', 'n', 'g', ' ']
#\A 匹配字符串开始 与 \Z 匹配字符串结束,如果存在换行,只匹配到换行前的字符串
print(re.findall('\Ah','hello long 123')) # ['h']
print(re.findall('123\Z','hello long 123')) # ['123']
# ^ 与 $
print(re.findall('^h','hello long 123')) # ['h']
print(re.findall('3$','hello long 123')) # ['3']
# 重复匹配:. * ? .* .*? + {n,m}
#. 匹配任意的字符,(除了\n)
print(re.findall('a.b','a2b')) # ['a2b']
print(re.findall('a.b','a1b a*b a b asdb')) # ['a1b', 'a*b', 'a b']
print(re.findall('a.b','a\nb')) #[]
print(re.findall('a.b','a\nb',re.S)) #['a\nb'] re.S 让.匹配叶包含\n
#* 0次 或 多次 前面的原子
print(re.findall('ab*','abbbb')) # ['abbbb']
print(re.findall('ab*','asss')) # ['a']
#* 0次 或 多次 前面的原子
print(re.findall('ab*','abbbb')) # ['abbbb'] # 贪婪的
print(re.findall('ab*','asss')) # ['a']
# ? 0次 或 1次 前面的原子
print(re.findall('ab?','abbbb')) # ['ab'] # 贪婪的
print(re.findall('ab?','asss')) # ['a']
#+ 1次 或 多次 前面的原子
print(re.findall('ab+','asss')) #[]
print(re.findall('ab+','abbb')) #['abbb']
#匹配所有包含小数在内的数字
print(re.findall('\d+\.?\d*','asdfasdf123as1.13dfa12adsf1asdf3')) # ['123', '1.13', '12', '1', '3']
#.* 默认为贪婪匹配(尽可能多的匹配)
print(re.findall('a.*b','a1b22222222b')) #['a1b22222222b']
#.*?为非贪婪匹配:推荐使用
print(re.findall('a.*?b','a1b22222222b')) # ['a1b']
# {n}精确匹配n个前面的原子 {n,m} 匹配n到m次前面出现的原子,贪婪模式
print(re.findall('ab{2}','abbb')) #['abb']
print(re.findall('ab{2,4}','abbb')) #['abbb']
print(re.findall('ab{1,}','abbb')) #'ab{1,}' ===> 'ab+' 1,+无穷 ['abbb']
print(re.findall('ab{0,}','abbb')) #'ab{0,}' ===> 'ab*' ['abbb']
#[] 匹配任意一个字母 [] 中的. * ? + 将会失效 [^] 表示取反
print(re.findall('a[1*+-]b','a1b a*b a-b a+b')) # ['a1b', 'a*b', 'a-b', 'a+b'] 如果-没有被转意的话,应该放到[]的开头或结尾
print(re.findall('a[^1*-]b','a1b a*b a-b a=b')) #[]内的^代表的意思是取反,所以结果为['a=b']
print(re.findall('a[1-9]b','a1b a*b a-b a=b')) # ['a1b']
print(re.findall('a[a-z]b','a1b a*b a-b a=b aeb')) # ['aeb']
print(re.findall('a[a-zA-Z]b','a1b a*b a-b a=b aeb aEb')) # ['aeb', 'aEb']
#\
# print(re.findall('a\\c','a\c')) #对于正则来说a\\c确实可以匹配到a\c,但是在python解释器读取a\\c时,会发生转义,然后交给re去执行,所以抛出异常
print(re.findall(r'a\\c','a\c')) #r代表告诉解释器使用rawstring,即原生字符串,把我们正则内的所有符号都当普通字符处理,不要转义 ['a\\c']
print(re.findall('a\\\\c','a\c')) #同上面的意思一样,和上面的结果一样都是['a\\c']
# ():分组
print(re.findall('ab+','ababab123')) #['ab', 'ab', 'ab']
print(re.findall('(ab)+123','ababab123')) #['ab'],匹配到末尾的ab123中的ab
print(re.findall('(?:ab)+123','ababab123')) #findall的结果不是匹配的全部内容,而是组内的内容,?:可以让结果为匹配的全部内容
print(re.findall('href="(.*?)"','<a href="http://www.baidu.com">点击</a>')) # ['http://www.baidu.com']
print(re.findall('href="(?:.*?)"','<a href="http://www.baidu.com">点击</a>')) # ['href="http://www.baidu.com"']
# ?<name> 不做任何匹配,将组中匹配的内容 赋值 给 name
data = re.search('(?P<name>[a-z|A-Z]+)(?P<age>\d+)','long18xiaoming20') # search只匹配第一个
print(data) # 若匹配成功,返回一个对象 否组返回None <_sre.SRE_Match object; span=(0, 16), match='long18xiaoming20'>
print(data.groups()) # 查看返回结果 ('long', '18') #
print(data.group('name')) # 获取name值 long
# | 选择符号 a|b pyhton|java
print(re.findall('pyhton|java','pyhton and java')) # ['pyhton', 'java']
print(re.findall('compan(?:y|ies)','Too many companies have gone bankrupt, and the next one is my company'))
# ['companies', 'company']
# ===========================re模块提供的方法介绍===========================
import re
#1
print(re.findall('e','alex make love') ) #['e', 'e', 'e'],返回所有满足匹配条件的结果,放在列表里
#2
print(re.search('e','alex make love').group()) #e,只到找到第一个匹配然后返回一个包含匹配信息的对象,该对象可以通过调用group()方法得到匹配的字符串,如果字符串没有匹配,则返回None。
#3
print(re.match('e','alex make love')) #None,同search,不过在字符串开始处进行匹配,完全可以用search+^代替match
#4
print(re.split('[ab]','abcd')) # ['', '', 'cd'] 先按'a'分割得到''和'bcd',再对''和'bcd'分别按'b'分割
#5 sub(pattern, repl, string, count=0, flags=0)
print(re.sub('l','L','long make love')) # Long make Love 将l全部替换L
print(re.sub('l','L','long make love',1)) # Long make love 只替换1个
print('===>',re.sub('^(\w+)(.*?\s)(\w+)(.*?\s)(\w+)(.*?)$',r'\5\2\3\4\1','long make love')) #===> love make alex
# 调整顺序
print(re.subn('l','L','long make love')) # ('Long make Love', 2) 会显示替换了几次
#6
obj=re.compile('\d{2}') # 规则已经编译到对象了
print(obj.search('abc123eeee').group()) #12
print(obj.findall('abc123eeee')) #['12'],重用了obj
#7
iters = re.finditer('\d+','as2dsf3d996fd') # 返回一个迭代器(适合数据很多时处理)
print(iters) # <callable_iterator object at 0x000001912161A6A0>
print(iters.__next__()) # <_sre.SRE_Match object; span=(2, 3), match='2'>
print(iters.__next__().group()) # 3
print(iters.__next__().group()) # 996
补充一:
import re
'''
group() == group(0) == 所有匹配的字符,与括号无关
groups() 返回所有括号匹配的字符,以tuple格式。
'''
print(re.findall("<(?P<tag_name>\w+)>\w+</(?P=tag_name)>",'<h1>hello</h1>')) # ['h1']
print(re.search("<(?P<tag_name>\w+)>\w+</(?P=tag_name)>",'<h1>hello</h1>').group(0)) # <h1>hello</h1>
print(re.search("<(?P<tag_name>\w+)>\w+</(?P=tag_name)>",'<h1>hello</h1>').groupdict()) # {'tag_name': 'h1'}
print(re.search('<(\w+)>\w+</(\w+)>','<h1>hello</h1>').group()) # <h1>hello</h1>
print(re.search(r"<(\w+)>\w+</\1>","<h1>hello</h1>").group()) # <h1>hello</h1>
补充二:
import re
#找出所有整数 -?\d+\.\d* 匹配出小数
print(re.findall('-?\d+\.\d*|(-?\d+)',"1-2*(60+(-40.35/5)-(-4*3))")) # ['1', '-2', '60', '', '5', '-4', '3']
#找到所有数字:
print(re.findall(r'\D?(-?\d+\.?\d*)',"1-2*(60+(-40.35/5)-(-4*3))")) # ['1', '2', '(60', '(-40.35', '5', '(-4', '3']
练习:
import re
#最常规匹配
content='Hello 123 456 World_This is a Regex Demo'
res=re.match('Hello\s\d\d\d\s\d{3}\s\w{10}.*Demo',content)
print(res)
print(res.group())
print(res.span())
#泛匹配
content='Hello 123 456 World_This is a Regex Demo'
# res=re.match('^Hello.*Demo',content)
# print(res.group())
#匹配目标,获得指定数据(数字)
content='Hello 123 456 World_This is a Regex Demo'
res=re.match('^Hello\s(\d+)\s(\d+).*Demo$',content)
print(res.group())
print(res.group(1)) # 获取第一个组
print(res.group(2)) # 获取第二个组
#贪婪匹配:.*代表匹配尽可能多的字符
content='Hello 123 456 World_This is a Regex Demo'
res=re.match('^He.*(\d+).*Demo$',content)
print(res.group(1)) #只打印6,因为.*会尽可能多的匹配,然后后面跟至少一个数字
#非贪婪匹配:?匹配尽可能少的字符
content='Hello 123 456 World_This is a Regex Demo'
res=re.match('^He.*?(\d+).*Demo$',content)
print(res.group(1)) #123
#匹配模式:.不能匹配换行符
content='''Hello 123456 World_This
is a Regex Demo
'''
res=re.match('He.*?(\d+).*?Demo$',content)
print(res) #输出None
res=re.match('He.*?(\d+).*?Demo$',content,re.S) #re.S让.可以匹配换行符
print(res)
print(res.group(1)) # 123456
#转义:\
content='price is $5.00'
res=re.match('price is $5.00',content)
print(res) # None
res=re.match('price is \$5\.00',content)
print(res.group())
#总结:尽量精简,详细的如下
# 尽量使用泛匹配模式.*
# 尽量使用非贪婪模式:.*?
# 使用括号得到匹配目标:用group(n)去取得结果
# 有换行符就用re.S:修改模式
#re.search:会扫描整个字符串,不会从头开始,找到第一个匹配的结果就会返回
import re
content='Extra strings Hello 123 456 World_This is a Regex Demo Extra strings'
res=re.match('Hello.*?(\d+).*?Demo',content) # 从开始处进行匹配
print(res) #输出结果为None
import re
content='Extra strings Hello 123 456 World_This is a Regex Demo Extra strings'
res=re.search('Hello.*?(\d+).*?Demo',content) #
print(res.group(1)) #输出结果为123
import re
content='''
<div id="topics">
<div class="post">
<h1 class="postTitle">
<a id="cb_post_title_url" class="postTitle2" href="https://www.cnblogs.com/linhaifeng/p/7278389.html">Python开发之路</a>
</h1>
<div class="clear"></div>
<div class="postBody">
<div id="cnblogs_post_body" class="blogpost-body "><a name="_labelTop"></a><div id="navCategory"><p style="font-size:25px"><b>阅读目录</b></p><ul></ul></div>
<p>详细内容见老男孩<<python入门与提高实践>></p>
<p><a href="http://www.cnblogs.com/linhaifeng/articles/7133167.html" target="_blank"><span style="font-size: 14pt;">第一篇:python入门</span></a></p>
<p><a href="http://www.cnblogs.com/linhaifeng/articles/7133357.html" target="_blank"><span style="font-size: 14pt;">第二篇:数据类型、字符编码、文件处理</span></a></p>
<p><a href="http://www.cnblogs.com/linhaifeng/articles/7532512.html" target="_blank"><span style="font-size: 14pt;">第三篇:函数</span></a></p>
<p><a href="http://www.cnblogs.com/linhaifeng/articles/6379069.html" target="_blank"><span style="font-size: 14pt;">第四篇:模块与包</span></a></p>
<p><a href="http://www.cnblogs.com/linhaifeng/articles/6384466.html" target="_blank"><span style="font-size: 14pt;">第五篇:常用模块</span></a></p>
<p><a href="http://www.cnblogs.com/linhaifeng/articles/6182264.html" target="_blank"><span style="font-size: 14pt;">第六篇:面向对象</span></a></p>
<p><a href="http://www.cnblogs.com/linhaifeng/articles/6204014.html" target="_blank"><span style="font-size: 14pt;">第七篇:面向对象高级</span></a></p>
<p><a href="http://www.cnblogs.com/linhaifeng/articles/6232220.html" target="_blank"><span style="font-size: 14pt;">第八篇:异常处理</span></a></p>
<p><a href="http://www.cnblogs.com/linhaifeng/articles/6129246.html" target="_blank"><span style="font-size: 14pt;">第九篇:网络编程</span></a></p>
<p><a href="http://www.cnblogs.com/linhaifeng/articles/6817679.html" target="_blank"><span style="font-size: 14pt;">第十篇:并发编程</span></a></p>
<p><a href="http://www.cnblogs.com/linhaifeng/articles/7356064.html" target="_blank"><span style="font-size: 14pt;">第十一篇:Mysql系列</span></a></p>
<p><span style="font-size: 14pt;">更新中...</span></p>
</div>
<div id="MySignature"></div>
<div class="clear"></div>
<div id="blog_post_info_block">
<div id="blog_post_info">
<div id="green_channel">
<a href="javascript:void(0);" id="green_channel_digg">已推荐</a>
<a id="green_channel_follow" href="javascript:void(0);">已关注</a>
<a id="green_channel_favorite" onclick="AddToWz(cb_entryId);return false;" href="javascript:void(0);">收藏该文</a>
<a id="green_channel_weibo" href="javascript:void(0);" title="分享至新浪微博" onclick="ShareToTsina()"><img src="https://common.cnblogs.com/images/icon_weibo_24.png" alt=""></a>
<a id="green_channel_wechat" href="javascript:void(0);" title="分享至微信" onclick="shareOnWechat()"><img src="https://common.cnblogs.com/images/wechat.png" alt=""></a>
</div>
<div id="author_profile">
<div id="author_profile_info" class="author_profile_info">
<a href="https://home.cnblogs.com/u/linhaifeng/" target="_blank"><img src="https://pic.cnblogs.com/face/1036857/20161007110720.png" class="author_avatar" alt=""></a>
<div id="author_profile_detail" class="author_profile_info">
<a href="https://home.cnblogs.com/u/linhaifeng/">linhaifeng</a><br>
<a href="https://home.cnblogs.com/u/linhaifeng/followees/">关注 - 0</a><br>
<a href="https://home.cnblogs.com/u/linhaifeng/followers/">粉丝 - 4238</a>
</div>
</div>
<div class="clear"></div>
<div id="author_profile_honor"></div>
<div id="author_profile_follow">
我在关注他 <a href="javascript:void(0);" onclick="unfollow('66b39f18-c28a-e611-845c-ac853d9f53ac');return false;">取消关注</a>
</div>
</div>
<div id="div_digg">
<div class="diggit" onclick="votePost(7278389,'Digg')">
<span class="diggnum" id="digg_count">130</span>
</div>
<div class="buryit" onclick="votePost(7278389,'Bury')">
<span class="burynum" id="bury_count">6</span>
</div>
<div class="clear"></div>
<div class="diggword" id="digg_tips">
您已推荐过,<a href="javascript:void(0);" onclick="votePost(7278389,'Digg', true);return false;" class="digg_gray">取消</a>
</div>
</div>
<script type="text/javascript">
currentDiggType = 1;
</script></div>
<div class="clear"></div>
<div id="post_next_prev">
<a href="https://www.cnblogs.com/linhaifeng/p/6716477.html" class="p_n_p_prefix">« </a> 上一篇: <a href="https://www.cnblogs.com/linhaifeng/p/6716477.html" title="发布于 2017-04-15 23:59">GRE与VXLAN</a>
<br>
<a href="https://www.cnblogs.com/linhaifeng/p/8241221.html" class="p_n_p_prefix">» </a> 下一篇: <a href="https://www.cnblogs.com/linhaifeng/p/8241221.html" title="发布于 2018-01-08 09:49">爬虫课程</a>
</div>
</div>
</div>
<div class="postDesc">posted @
<span id="post-date">2017-08-03 10:34</span> <a href="https://www.cnblogs.com/linhaifeng/">linhaifeng</a> 阅读(<span id="post_view_count">147438</span>) 评论(<span id="post_comment_count">30</span>) <a href="https://i.cnblogs.com/EditPosts.aspx?postid=7278389" rel="nofollow"> 编辑</a> <a href="javascript:void(0)" onclick="AddToWz(7278389); return false;">收藏</a>
</div>
</div>
</div>
'''
#re.search:只要一个结果,匹配演练,
# <p><a href="http://www.cnblogs.com/linhaifeng/articles/7133167.html" target="_blank"><span style="font-size: 14pt;">第一篇:python入门</span></a></p>
res=re.search('<p><a\shref="(.*?)".*</p>',content)
print(res.group(1))
# re.findall:找到符合条件的所有结果
res=re.findall('<p><a\shref="(.*?)".*</p>',content)
for i in res:
print(i)
#re.sub:字符串替换
import re
content='Extra strings Hello 123 456 World_This is a Regex Demo Extra strings'
content=re.sub('\d+','',content)
print(content) # Extra strings Hello World_This is a Regex Demo Extra strings
#用\1取得第一个括号的内容
#用法:将123与456换位置
import re
content='Extra strings Hello 123 456 World_This is a Regex Demo Extra strings'
content=re.sub('(Extra.*?)(\d+)(\s)(\d+)(.*?strings)',r'\1\4\3\2\5',content)
# content=re.sub('(\d+)(\s)(\d+)',r'\3\2\1',content)
print(content)
import re
content='Extra strings Hello 123 456 World_This is a Regex Demo Extra strings'
res=re.search('Extra.*?(\d+).*strings',content)
print(res.group(1))
练习2:
import re
'''
1、匹配整数或者小数(包括正数和负数)
-?\d+(\.\d+)?
-?表示-匹配0次或一次,\d表示整数,+表示匹配一次或多次,(\.\d+)?表示小数 ?:显示全部匹配的
'''
res = re.findall('-?\d+(?:\.\d+)?','1-2+3-(-5.52*6)-55')
print(res)
'''
2、匹配年月日日期 格式2018-12-6
^[1-9]\d{0,3}-(1[0-2]|0?[1-9])-(3[01]|[12]\d|0?[1-9])$
1.^[1-9]表示年是以数字1-9开头的,\d{0,3}表示年的位数,^[1-9]\d{0,3}就表示1-9999年之间
2.(1[0-2]|0?[1-9])中|前面的1[0-2]表示从10到12,后面的0?[1-9]表示01-09或者1-9,
(1[0-2]|0?[1-9])表示月,01-12或者1-12
3.(3[01]|[12]\d|0?[1-9])$其中3[01]表示30或31,[12]\d表示从10-29,最后的0?[1-9]表示从
01-09或者是从1-9.整体就表示从01-31或者1-31
'''
res = re.search('(^\d{0,4})-(0?[1-9]|1[1-2])-(0?[1-9]|3[01]|[12][0-9])','2019-12-27')
print(res.group())
res = re.search('(^\d{0,4})-(0?[1-9]|1[1-2])-(0?[1-9]|3[01]|[12][0-9])','2019-01-27')
print(res.group())
res = re.search('(^\d{0,4})-(0?[1-9]|1[1-2])-(0?[1-9]|3[01]|[12][0-9])','2019-01-3')
print(res.group())
'''
3、匹配qq号
[1-9]\d{4,11}
表示5位到12位qq.第一位为非0
'''
res = re.search('[1-9]\d{4,11}','123456')
print(res.group())
res = re.search('[1-9]\d{4,11}','845970361')
print(res.group())
'''
4、11位的电话号码
1[3-9]\d{9}
第一位数字为1,第二位为3-9,后面随便9位数
'''
res = re.search('1[3-9]\d{9}','17802580286')
print(res.group())
'''
5、长度为8-15位的用户密码 : 包含数字字母下划线
\w{8,10}
'''
res = re.search('\w{8,15}','hechaolong123_')
print(res.group())
'''
6、匹配验证码:4位数字字母组成的
[\da-zA-Z]{4}或者[0-9a-zA-Z]{4}
[ ]里面的表示数字,或者a-z或者A-Z,{4}表示4位
'''
res = re.search('[\da-zA-Z]{4}','Ap5E')
print(res.group())
'''
7、匹配邮箱地址
[0-9a-zA-Z][\w\-.]+@[a-zA-Z0-9\-]+(\.[a-zA-Z0-9\-]+)*\.[A-Za-z0-9]{2,6}
[0-9a-zA-Z][\w\-.]+ @前面必须有内容且只能是字母(大小写),数字,下划线,减号,点
[a-zA-Z0-9\-]+(\.[a-zA-Z0-9\-]+)* @和最后一个点之间必须有内容且只能是字母(大小写),数字,点,减号,且两个点不能挨着
[A-Za-z0-9]{2,6} 最后一个点之后必须有内容且内容只能是字母(大小写),数字长度为大于等于2,小于等于6
'''
res = re.search('[\da-zA-Z][\w\-.]+@[\da-zA-Z\-]+(\.[a-zA-Z\d\-]+)*\.[A-Za-z\d]{2,6}','long_1-2.3@163-123.com.cn')
print(res.group())
'''
8、从类似
<a>wahaha</a>
<b>banana</b>
<h1>qqxing</h1>
这样的字符串中,
1)匹配出wahaha,banana,qqxing内容。
\w{6}
>\w+<
2)匹配出a,b,h1这样的内容
<\w+>
'''
res = re.search('<a\s*href="(.*?)">(.*?)</a>','<a href="www.baidu.com">百度</a>')
print(res.groups()) # ('www.baidu.com', '百度')
'''
9、1-2*((60-30+(-40/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))
1)从上面算式中匹配出最内层小括号以及小括号内的表达式
\([^()]+\) \(和\)表示前后位( ),[^()]就表示外面的()里面没有()
'''
res = re.search('\([^()]+\)','1-2*((60-30+(-40/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))')
print(res.group())
'''
10、从类似9-2*5/3+7/3*99/4*2998+10*568/14的表达式中匹配出从左到右第一个乘法或除法
\d+[*/]\d+ [*/]前后的\d+表示*或/前面的整数,可能是多位数字,要加+
'''
res = re.search('\d+[.\d]*[*/]\d+[.\d]*','9-2*5.25/3+7/3*99/4*2998+10*568/14')
print(res.group()) # 2*5.25