python——正则表达式

python——正则表达式

1. 正则表达式

  • 正则表达式(regular expression)描述了一种字符串匹配的模式(pattern),可以用来检查一个串是否含有某种子串、将匹配的子串替换或者从某个串中取出符合某个条件的子串等。

2. 正则表达式的字符对应功能

在这里插入图片描述

2.1 特殊字符

在这里插入图片描述

2.2 数量限定字符

在这里插入图片描述

2.3 位置字符

在这里插入图片描述

3.正则表达式的匹配类型

使用正则表达式有两种方式

  1. 创建正则表达式对象,调用函数————使用多次
  2. 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号不符合要求!')
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值