python爬虫之正则表达式程序
2018-07-30 18:57
141 查看
# re.match(pattern,string,flags=0) # pattern:正则表达式 # string:字符串 # flags:匹配模式 # import re # content = 'hello sdhcjd ajdvqn acdeu akdj qsdwr 123 456' # print(len(content)) # result = re.match('hello',content) # print(result) # print(result.group()) # 返回匹配结果 # print(result.span()) # 输入匹配结果的范围 # 泛匹配 # import re # content = 'hello sdancq ancje ncjewcfb cjaaduwe' # result = re.match('^hello.*',content) # 使用.*匹配所有 # print(result.group()) # 匹配目标 import re # content = 'hello 123 ancje ncjewcfb cjaaduwe de' # result = re.match('^hello\s(\d+)\sancje.*de$', content) # print(result.group(1)) #数字1表示第一个括号的内容 即123 # 贪婪匹配 # import re # content = 'hello 123 ancje ncjewcfb cjaaduwe de' # # result = re.match('^hello.*(\d+)\sancje.*de$', content) # result = re.match('^hello.*?(\d+)\sancje.*de$', content) # $指定结尾 # # 非贪婪匹配:在.*的后面加一个?,匹配尽可能少的括号里的内容 # print(result.group(1)) # 贪婪匹配指括号前面.*的操作,一直匹配到只有一个括号里的内容为止。 # 匹配模式 # import re # content = 'hello 123 dcj ds jfs' # reslt = re.match('^hello\s.*?(d+).*$',content,re.S) # # 因为.*无法匹配换行符,使用re.S则可以匹配换行符 # 匹配特殊字符:使用转义字符\ # import re # content = 'price is $10' # result = re.match('^price is \$10',content) # print(result.group()) # 尽量使用泛匹配和非贪婪模式 # re.search() # 扫描整个字符串,返回第一个成功匹配的字符串 # import re # content = 'hello 123 djak 123 fwjgr' # result = re.search('123',content) # print(result.group()) # re.findall() # 返回全部能匹配的字串 # import re # content = 'hello 123 dsjvo 123 sjdifro' # result = re.findall('123',content) # print(result) #以列表的形式输出 # for r in result: # print(r) # re.sub() # 替换字符串中每一个匹配的字串后返回替换后的内容 # 将数字换成固定字符 # import re # content = 'Extra 123 adshua ashdw asdjkef' # result = re.sub('\d+', 'replace', content) # print(result) # re.compile() # 将正则字符串编译成正则表达式对象,便于复用该匹配对象 import re # content = 'Hello 1234567 kcdjchv sv' # pattern = re.compile('Hello.*sv') # result = re.search(pattern,content) # 复用匹配模式 # print(result) # print(result.group())阅读更多
相关文章推荐
- Python 爬虫小程序(正则表达式的应用)
- 04 Python正则表达式 爬虫程序 变量的引用,浅拷贝,深拷贝 多线程 进程锁 数据库模块
- Python 3爬虫网易云(五)—— 正则表达式下篇之HTML标签
- (转)Python爬虫学习笔记(2):Python正则表达式指南
- python3爬虫入门之正则表达式
- Python爬虫入门(7):正则表达式
- 06Python爬虫---正则表达式04之常用表达式
- python 爬虫004-使用urllib2与正则表达式扒取糗事百科新鲜页首页帖子
- python爬虫学习---正则表达式的使用
- 正则表达式基础——以Python爬虫为实例
- python爬虫提取信息:正则表达式和xpath
- python3爬虫之入门和正则表达式
- 【Python3 爬虫】08_正则表达式(元字符与语法)
- Python爬虫入门(7):正则表达式
- python3爬虫初级入门和正则表达式
- python爬虫学习(1)--关于正则表达式输入和提取中文
- Python3.7 爬虫(一)使用 Urllib2 与正则表达式抓取
- Python爬虫学习纪要(五):正则表达式2
- python爬虫之re正则表达式库
- python实现简单爬虫以及正则表达式简述