python爬虫之路——Python的re模块及其方法

介绍常用的三种方法:search(),sub(),findall()

 search():匹配并提取第一个符合规律的内容,然后返回一个正则表达式的对象

#提取字符串中的第一个数字

import re

a='a1b2d3f4'

infos=re.search('d+',a)

print(infos)

#返回一个正则表达式的对象

print(infos.group())

#return 1

sub():替换

import re

phone='123-456-789'

new_phone=re.sub('D','',phone)

print(new_phone)

#return 123456789

findall():提取所有符合规律的内容,并返回一个列表。

import re

phone='123-456-789'

new_phone=re.findall('d+','',phone)

print(new_phone)

#return ['123','456','789']

非贪心算法提取所有符合规律的字符串

import re

import request

re=requests.get('http://nj.xiaozhu.com/search-duanzufang-p2-0/')

prices=re.findall('<div class="day_l">¥<span>(.*?)</span><em>起</em></div>',res.test)

for prince in prices:

print(price)

re模块修饰符重点:re.I:大小写不敏感      re.S:换行匹配

prices=re.findall('<div class="day_l">¥<span>(.*?)</span><em>起</em></div>',res.test,re.S)

原文地址:https://www.cnblogs.com/lanbofei/p/8743541.html