python——正则表达式
文章目录
1. 正则表达式
- 正则表达式(regular expression)描述了一种字符串匹配的模式(pattern),可以用来检查一个串是否含有某种子串、将匹配的子串替换或者从某个串中取出符合某个条件的子串等。
2. 正则表达式的字符对应功能
2.1 特殊字符
2.2 数量限定字符
2.3 位置字符
3.正则表达式的匹配类型
使用正则表达式有两种方式
- 创建正则表达式对象,调用函数————使用多次
re.
调用函数————只使用1~2次
常用函数
函数名 | 描述 | 返回值 |
---|---|---|
match | 从前往后依次匹配 | 成功返回re.Match对象,否则返回None |
fullmatch | 从前往后依次匹配,完整匹配 | 成功返回re.Match对象,否则返回None |
search | 在字符串种进行搜索 | 匹配成功返回re.Match对象,否则返回None |
findall | 找到所有满足匹配模式的字符串 | 成功返回一个列表,否则返回一个空列表 |
3.1 单字符匹配
content = 'hell world 2021/8/14'
result = re.match(r'h', content) # matc只只根据匹配模式进行匹配,成功就返回
if result:
print(result.group()) # h
3.2 多字符匹配
content = 'hello world 2021/8/14'
result = re.match(r'hello', content)
if result:
print(result.group())
3.3 指定字符匹配
content = 'hello world 2021/8/14'
result = re.match(r'[\w]*', content)
if result:
print(result.group())
search函数进行匹配
import re
content = 'hello world 2021/8/14'
result = re.search(r'[\w]*', content)
if result:
print(result.group()) # hello
find进行匹配
import re
content = 'hello world 2021/8/14'
result = re.findall(r'[\w]+', content)
if result:
print(result) # ['hello', 'world', '2021', '8', '14']
group():取出匹配部分
split():分割,返回列表
import re
content = 'hello world 2021/8/14'
result = re.split(' ', content) # 用空格进行分割,返回列表
print(result) # ['hello', 'world', '2021/8/14']
sub():替换字符
import re
content = 'hello world 2021/8/14'
result = re.sub(r'14', '13', content) # 将14替换为13
print(result)
content = 'hello world 2021/8/14'
result = re.sub(r'[\d]+', '', content) # 将数字特换为空
print(result)
捕获组:匹配时全部匹配,只返回捕获组匹配的内容,以元组的类型返回,用于过滤字符内容
4. 正则表达式的应用
- 正则表达式在网络数据采集上使用的比较平凡效率比较高,正则表达式实际写起来也是非常困难的一件事。
获取搜狐网首页上的链接
import re
import requests
match = re.compile(r' href=".+?"') # 创建正则表达式对象
resp = requests.get(url='https://www.sohu.com/') # 获取搜狐网连接,得到一个responser对象
content = resp.text # 得到返回的网页源代码内容,类型为字符串
href_list = match.findall(content) # 获取网页源代码中的链接字符串
for href in href_list:
link = href[7:-1]
print(link)
判断QQ号是否合法
import re
pattern = re.compile(r'[1-9][0-9]{5,}')
qq = input('输入qq号:')
result = pattern.match(qq)
if result:
print(qq)
else:
print('qq号不符合要求!')