【Python3 爬虫】09_正则表达式(re.math()、re.search()、re.sub()、全局匹配函数)
2018-03-27 15:07
1116 查看
re.math()函数
从源字符串的起始位置匹配一个模式语法:re.match(pattern, string, flag)
第一个参数代表对应的正则表达式,第二个参数代表对应的源字符,第三个参数是可选参数,代表对应的标志位,可以放模式修正符等信息
#-*- codingn:utf-8 -*- import re string = "ipythonajsoasaoso" pattern = ".python." result = re.match(pattern, string) result1 = re.match(pattern, string).span() print("结果1:%s" % result)
print(result1) # (0,8)
re.search()函数
扫描整个字符串进行匹配语法:re.search(pattern, string, flag)
#-*- codingn:utf-8 -*- import re string = "helloipythonajsoasaoso" pattern = ".python." result1 = re.match(pattern, string) result2 = re.search(pattern, string) print("结果1:%s" % result1) print("结果2:%s" % result2)
全局匹配函数
将符合模式的全部内容都匹配出来(1)使用re.compile()对正则表达式进行预编译(2)编译后使用findall()根据正则表达式从原字符串中将匹配的解决全部找出
#-*- codingn:utf-8 -*- import re string = "helloipythonajsoasaospythono" pattern = re.compile(".python.") #预编译 result = pattern.findall(string) #找出符合模式的所有结果 print("结果1:%s" % result)
re.sub()函数
根据正则表达式来实现替换某些字符串re.sub(pattern, rep, string, max)
第一个参数对应的正则表达式,第二个参数为要替换成的字符串,第三个参数为源字符串,第四个参数为可选项,代表最多替换的次数,如果忽略不写,则会将符合模式的结果全部替换。
#-*- codingn:utf-8 -*- import re string = "bnsdBBjsdkBBlsBBdkBBs" pattern = "BB" result1 = re.sub(pattern,"**",string) #全部替换 result2 = re.sub(pattern,"**",string,1) #最多替换1次 result3 = re.sub(pattern,"**",string,2) #最多替换2次 print("结果1:%s" % result1) print("结果2:%s" % result2) print("结果3:%s" % result3)
相关文章推荐
- python中,有关正则表达式re函数:compile、match、search、findall
- python基础===正则表达式,常用函数re.split和re.sub
- python正则表达式模块,re.sub的函数使用
- Python - 正则表达式 re.match/re.search/re.sub
- python正则表达式 re (二)sub
- python爬虫常用正则表达式组合匹配
- python正则表达式 re (二)匹配对象和组
- Python中正则表达式match()、search()函数及match()和search()的区别详解
- python学习:python中的正则表达式函数match和search()的区别
- python爬虫学习笔记6:正则表达式及re库
- python里使用正则表达式的groups()函数访问组匹配串
- Python正则表达式中的 compile,search,group,groups 函数的简单说明
- Python: 字符串搜索和匹配,re.compile() 编译正则表达式字符串,然后使用match() , findall() 或者finditer() 等方法
- python里使用正则表达式的search()函数实现指定位置搜索
- python3爬虫(二) re模块与正则表达式
- python爬虫入门(2)re模块-正则表达式
- python re模块学习--正则表达式函数
- Python 正则表达式,边界匹配(search)
- python正则表达式 re (二)sub
- python3正则表达式简单使用、search()、match()等函数的区别