学会Python正则表达式,就看这20个例子(脚本之家(2)

import re s='This module provides regular expression matching operations similar to those found in Perl' pat=r'^([mt][a-zA-Z]*)\s' # 查找以 r=re.compile(pat,re.I).findall(s) print(r) #['This']

13、先分割,再查找满足要求的单词

使用match表示是否匹配

import re s='This module provides regular expression matching operations similar to those found in Perl' pat=r'\s+' r=re.split(pat,s) res=[i for i in r if re.match(r'[mMtT]',i)] print(res) #['This', 'module', 'matching', 'to', 'those']

14、贪心匹配

尽可能多的匹配字符

import re content='<h>ddedadsad</h><div>graph</div>bb<div>math</div>cc' pat=re.compile(r"<div>(.*)</div>") #贪婪模式 m=pat.findall(content) print(m) #['graph</div>bb<div>math']

15、非贪心匹配

与14相比,仅仅多了一个问号(?),得到结果完全不同。

import re content='<h>ddedadsad</h><div>graph</div>bb<div>math</div>cc' pat=re.compile(r"<div>(.*?)</div>") #贪婪模式 m=pat.findall(content) print(m) #['graph', 'math']

与14比较可知,贪心匹配和非贪心匹配的区别,后者是字符串匹配后立即返回,见好就收。

16、含有多种分割符

使用split函数

import re content = 'graph math,,english;chemistry' #这种 pat=re.compile(r"[\s\,\;]+") #贪婪模式 m=pat.split(content) print(m) #['graph', 'math', 'english', 'chemistry']

17、替换匹配的子串

sub函数实现对匹配子串的替换

import re content="hello 12345, hello 456321" pat=re.compile(r'\d+') #要替换的部分 m=pat.sub("666",content) print(m) #hello 666, hello 666

18、爬取百度首页标题

import re from urllib import request #爬虫爬取百度首页内容 data=request.urlopen("http://www.baidu.com/").read().decode() #分析网页,确定正则表达式 pat=r'<title>(.*?)</title>' result=re.search(pat,data) print(result) #<re.Match object; span=(1389, 1413), match='<title>百度一下,你就知道</title>'>

下面是知识点分享

19、常用元字符总结

. 匹配任意字符  
^ 匹配字符串始位置 
$ 匹配字符串中结束的位置 
* 前面的原子重复0次1次多次 
? 前面的原子重复一次或者0次 
+ 前面的原子重复一次或多次
{n} 前面的原子出现了 n 次
{n,} 前面的原子至少出现 n 次
{n,m} 前面的原子出现次数介于 n-m 之间
( ) 分组,需要输出的部分

20、常用通用字符总结

\s 匹配空白字符
\w 匹配任意字母/数字/下划线
\W 和小写 w 相反,匹配任意字母/数字/下划线以外的字符
\d 匹配十进制数字
\D 匹配除了十进制数以外的值
[0-9] 匹配一个0-9之间的数字
[a-z] 匹配小写英文字母
[A-Z] 匹配大写英文字母

以上就是Python中正则模块的基本使用总结,里面有循序渐进的优化分析过程,这些虽然是中间过程,但是对于正则小白而言,了解这些很有必要。笔者对于正则的理解也比较肤浅,如有总结不到位之处,恳请指正。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wyggxp.html