re.match
从字符串的开始位置进行匹配,起始位置不匹配则停止
最常规的匹配
re.match(正则表达式字符串,待匹配对象,匹配模式)
import re
content='hello 123 4567 world'
result=re.match('^hello\s\d{3}\s\d{4}\sworld$',content)
print(result)
print(type(result))
print(result.group())#返回正则表达式对应的字符串信息
print(type(result.group()))
print(result.span())#字符串的起止索引
print(type(result.span()))
输出结果:
<_sre.SRE_Match object; span=(0, 20), match='hello 123 4567 world'>
<class '_sre.SRE_Match'>
hello 123 4567 world
<class 'str'>
(0, 20)
<class 'tuple'>
泛匹配
import re
content='hello 123 4567 world'
result=re.match('^hello.*world$',content)
print(result.group())
匹配目标
import re
content='hello 1234567 world'
result=re.match('^hello\s(\d+)\sworld$',content)
print(result.group())
print(result.group(1))
输出结果:
hello 1234567 world
1234567-->第一个小括号获得的内容
贪婪匹配
import re
content='hello 1234567 world'
result=re.match('^he.*(\d+).*ld$',content)
print(result.group(1))
输出结果:
7–>因为前面的.*已经是贪婪匹配把123456都匹配了,而+号至少匹配一个数字,所以匹配了7
非贪婪匹配
import re
content='hello 1234567 world'
result=re.match('^he(.*?)(\d+).*ld$',content)
print(result.group(1))
print(len(result.group(1)))
print(result.group(2))
输出结果:
llo
4
1234567
第一个小括号取得llo+空格;第二个小括号取得1234567
要注意的是.可以匹配除了换行符之外的任意字符,所以空格也可以匹配
匹配模式
re.S,使得.可以匹配换行符
转义
特殊字符前加上\,或者在正则表达式前面加上r
总结:尽量使用泛匹配、使用括号得到匹配目标、尽量使用非贪婪模式、有换行符就用re.S
re.search
扫描整个字符串并返回第一个成功匹配的内容
能使用search则不使用match
re.findall
搜索字符串,以列表形式返回全部能匹配的子串
re.sub
替换字符串中每一个匹配的子串后返回替换后的字符串
第一个参数是正则表达式,第二个参数是用来替换的字符串,第三个参数是目标字符串
**import re
content='hello 1234567 world'
result=re.sub('(\d+)',r'\1 8910',content)
print(result)**
输出结果:hello 1234567 8910 world
**
表示在保留第一个子组的基础上,在它后面加上’ 8910’
re.sub('a|b','2',content)
:content中的所有的a、b替换为2
re.compile
将正则表达式编译成正则表达式对象,以便复用该匹配模式
实例
import requests
import re
url='https://book.douban.com/'
headers={'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36'}
response=requests.get(url,headers=headers).text
pattern = re.compile('<li class.*?href="(.*?)".*?title="(.*?)">.*?src="(.*?)".*?class="author">(.*?)</div>.*?"year">(.*?)</span>',re.S)
booklist=re.findall(pattern,response)
for book in booklist:
print(book)