15-正则表达式

https://deerchao.cn/tutorials/regex/regex.htm

通配符作用举例注释
\b匹配单词的开始或结束\bhi\b匹配hi这个单词
.*匹配任意字符\bhi\b.*\bLucy\b匹配hi Lucy,这两个单词之间可以有任意个字符
\d匹配一位数字0\d\d-\d\d\d\d\d\d\d\d匹配电话号码
{}重复n次0\d{2}-\d{8}上面例子的优化
\s匹配任意空字符
\w匹配字母数字下划线\b\w{6}\b匹配六个字符的单词
^匹配字符串的开始
$匹配字符串的结束^\d{5,12}$只能输入5-12位的数字
\转义.查找元字符,需要先转义。匹配.
代码/语法说明
*重复零次或更多次
+重复一次或更多次
?重复零次或一次
{n}重复n次
{n,}重复n次或更多次
{n,m}重复n到m次
代码/语法说明
\W匹配任意不是字母,数字,下划线,汉字的字符
\S匹配任意不是空白符的字符
\D匹配任意非数字的字符
\B匹配不是单词开头或结束的位置
[^x]匹配除了x以外的任意字符
[^aeiou]匹配除了aeiou这几个字母以外的任意字符

Python中有两种方式使用正则:

  • 不创建对象,直接调用函数
  • 创建正则表达式对象(Pattern)compile

例子1:检查用户名

用户名在6到20个字符内,可以使用数字字母下划线:\w{6,20}

import re
username = input("请输入用户名:")
matcher = re.fullmatch(r"\w{6,20}", username)
# 或者re.match(r"^\w{6,20}$", username) 表示匹配一个单词的完整开头和结尾
if matcher is None:
    print("用户名不合法")
else:
    print(matcher.group())

第二种方式:

username = input("请输入用户名:")
username_pattern = re.compile(r"\w{6,20}")
print(type(username_pattern))
matcher = username_pattern.match(username)
if matcher is None:
    print("用户名不合法")
else:
    print(matcher.group())

例子2:search

如果是在某个比较长的字符串中匹配的话,要使用search

import re
content = """报警电话:110,我们班是xx2班,
我的QQ号是12345678,我的手机号是18237763193
"""
matcher = re.search(r"1[3-9]\d{9}", content)
if not matcher:
    print("没有找到手机号")
else:
    print(matcher.group())

如果需要查询所有的数字:

pattern = re.compile(r"\d+")
matcher2 = pattern.search(content)
while matcher2:
    print(matcher2.group())
    matcher2 = pattern.search(content, matcher2.end())

例子3:从网页上获取新闻标题和链接

findall—找出所有符合条件的内容,返回列表

import re
import requests

pattern1 = re.compile(r'href="http.+?"')
resp = requests.get("https://www.sohu.com/")
content = resp.text
matcher = pattern1.search(content)
while matcher:
    print(matcher.group()[6:-1])
    matcher = pattern1.search(content, matcher.end())

pattern2 = re.compile(r'title=".+?"')
titles_list = pattern2.findall(content)
for title in titles_list:
    print(title[7:-1])

例子4:捕获组,以此拿到对应的链接和标题

捕获括号中的内容

import re
import requests

pattern1 = re.compile(r'<a\s.*?href="(.+?)".*?title="(.+?)".*?>')
resp = requests.get("https://www.sohu.com/")
results = pattern1.findall(resp.text)
for href, title in results:
    print(title)
    if href.startswith("/a/") or href.startswith("/xtopic/"):
        href = "https://www.sohu.com" + href
    elif href.startswith("//"):
        href = "https:" + href
    print(href)

例子5:不良内容过滤

import re

content = "xxx是个傻逼"

# fixed_content = re.sub(r"[傻沙煞][逼吊刁]|fuck|shit", "*", content, count=0, flags=re.I)
pattern = re.compile(r"[傻沙煞][逼吊刁]|fuck|shit", flags=re.I)
fixed_content = pattern.sub("*", content)
print(fixed_content)

例子6:拆分字符串

import re

song = "春眠不觉晓,处处闻啼鸟。夜来风雨声,花落知多少。"
sens_list = re.split(r"[,。]", song)
# 这一步是为了去掉最后那个空字符串
sens_list = [sen for sen in sens_list if sen]
print(sens_list)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值