正则表达式和re库

本文最后更新于:2022年10月19日 晚上

相关网站

正则表达式测试 正则表达式部分笔记 b站网课

正则表达式

定义

一种使用表达式的方式对字符串进行匹配的的语法规则

使用条件

在python爬虫中数据解析部分,解析的局部的文本内容都会在标签之间或者标签对应的属性中进行存储,当要对存储的信息进行提取时,就要用到正则表达式。

语法

使用元字符进行排列组合用来匹配字符串

元字符

具有固定含义的特殊符号(默认匹配一位)

元字符 含义
. 匹配除换行符以外的任意字符
匹配字母或数字或下划线
匹配任意的空白符
匹配数字
匹配一个换行符
匹配一个制表符
^ 匹配字符串的开始
$ 匹配字符串的结尾
匹配非字母或数字或下划线
匹配非数字
匹配非空白符
a|b 匹配字符α或字符b
() 匹配括号内的表达式,也表示一个组
[...] 匹配字符组中的字符(a-z代表a到z所有的字母)
[^...] 匹配除了字符组中字符的所有字符

例子

1
2
3
4
5
6
7
8
eg:a11111
^\d\d\d\d\d 无匹配结果

eg:11111a
\d\d\d\d\d$ 无匹配结果

eg:我的电话是:10010
[我10] 我 1 0 0 1 0

量词

控制前面的元字符出现的次数

量词 含义
* 重复零次或更多次
+ 重复一次或更多次
重复零次或一次
{n} 重复n次
{n,} 重复n次或更多次
{n,m} 重复n到m次

匹配模式

.* 贪婪匹配 .*?懒惰匹配 在python爬虫中一般使用懒惰匹配

re模块

函数

pattern:正则表达式 ;string:字符串;flags:状态位,可嵌入的规则(re.S,re.M等)

函数 含义
compile(pattern, flags=0) 编译正则表达式返回正则表达式对象(预加载正则表达式)
match(pattern, string, flags=0) 用正则表达式匹配字符串,从头开始匹配 成功返回匹配对象 否则返回None
search(pattern, string, flags=0) 搜索字符串中第一次出现正则表达式的模式 成功返回匹配对象 否则返回None
split(pattern, string, maxsplit=0, flags=0) 用正则表达式指定的模式分隔符拆分字符串 返回列表
sub(pattern, repl, string, count=0, flags=0) 用指定的字符串替换原字符串中与正则表达式匹配的模式 可以用count指定替换的次数
fullmatch(pattern, string, flags=0) match函数的完全匹配(从字符串开头到结尾)版本
findall(pattern, string, flags=0) 查找字符串所有与正则表达式匹配的模式 返回字符串的列表
finditer(pattern, string, flags=0) 查找字符串所有与正则表达式匹配的模式 返回一个迭代器,从迭代器拿到内容
purge() 清除隐式编译的正则表达式的缓存
re.I / re.IGNORECASE 忽略大小写匹配标记
re.M / re.MULTILINE 多行匹配标记
re.S 单行匹配标记
(?P<分组名字>正则) 可以单独从正则匹配的内容中进一步提取内容(p要大写)

例子

1.findall()返回列表形式

1
2
3
4
ls=re.fiindall(r'\d+',"我的电话是:10086,他的电话是:10010.")
print(ls)

#['10086','10010']
2.finditer()返回迭代器
1
2
3
4
5
6
it=re.fiindall(r'\d+',"我的电话是:10086,他的电话是:10010.")
for i in it:
print(i.group())

#10086
10010
3.search()返回match对象
1
2
3
4
5
ls=re.search(r'\d+',"我的电话是:10086,他的电话是:10010.")
print(ls.group())

#10086
只返回第一个结果
4.match()从头开始匹配,与search()类似
1
2
3
4
5
6
7
8
ls=re.match(r'\d+',"10086,他的电话是:10010.")
print(ls.group())
#10086
ls=re.match(r'\d+',"我的电话是:10086,他的电话是:10010.")
print(ls.group())

#报错

5.compile()预加载正则表达式

1
2
3
4
5
6
7
8
9
obj = re.compile(r'\d')
ret = obj.finditer("我的电话号是:10086,我女朋友的电话是:10010")
for it in ret:
print(it.group())
ret = obj.findall("人口1000000")
print(ret)

#10086 10010
#['1000000']
6.(?P<分组名字>正则)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
s="<div class='a'><span id='1'>张三</span></div>
<div class='b'><span id='2'>李四</span></div>
<div class='c'><span id='3'>王五</span></div>
<div class='d' ><span id='4'>库里</span></div>
<div class='e'><span id='5'>汤普森</span></div>"
obj = re.compile(r"<div class='.*?'><span id=' (?P<id>\d+) '>(?P<name>.*?)</span></div>",re.S)
result = obj.finditer(s)
for it in result:
print(it.group( "name"))
print(it.group("id"))

#张三 1
李四 2
王五 3
库里 4
汤普森 5
7.re.S 将字符串作为一个整体匹配
1
2
3
4
5
6
7
8
9
a = "hello123
world"
b = re.findall('hello(.*?)world',a)
c = re.findall('hello(.*?)world',a,re.S)
print ('b = ' , b)
print ('c = ' , c)

# b =[] 空列表
# c =['123']


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!