正则表达式

正则表达式:

import re

s1 = 'python ui web 张三'

print(s1.find('web'))

print(re.search('web',s1)) #正则提供的精准查找

print(re.findall('web',s1)) #正则提供的模糊查找

t = '\d+'

print(re.findall(t,s1)) #通过正则查找字符串里的数字

#:t通配符:万能符,可以匹配\n以外的所有符号

s1 = 'tom 200 bom 308 do\nm 400 5e'

res1 = re.findall('[0-9]+',s1)

res2 = re.findall('[0-9]{1,}',s1)

res3 = re.findall('\d+',s1)

res4 = re.findall('\\d+',s1)

res5 = re.findall(r'\d+',s1)

res6 = re.findall(r'd|b+',s1)

res7 = re.findall(r'[tbd]om',s1)

res8 = re.findall(r'\n',s1)

res9 = re.findall(r'[0-9a-zA-Z]',s1)

print(res1)

print(res2)

print(res3)

print(res4)

print(res5)

print(res6)

print(res7)

print(res8)

print(res9)

s1 = 'aeeee age agree ape are a\ne ape a9e aFe'

reg = 'a.e'

res = re.findall(reg,s1)

res1 = re.findall('a.e',s1)

print(res1)

#2[]:表示字符串只能匹配一个

s2 = 'aeeee age agree ape are a\ne ape a9e aFe'

res1 = re.findall('a[p]e',s1)

res2 = re.findall('a[pg]e',s1)

res3 = re.findall('a[0-9]e',s1)

res4 = re.findall('a[a-z]e',s1)

res5 = re.findall('a[A-Z]e',s1)

res6 = re.findall('a[a-zA-Z]e',s1)

res7 = re.findall('a[^0-9]e',s1)

res8 = re.findall('a[^a-z]e',s1)

print(res1)

print(res2)

print(res3)

print(res4)

print(res5)

print(res6)

print(res7)

print(res8)

#{}制定左侧可以重复的范围

s3 = 'aeeee age agree ape are a\ne ape a9e aFe'

res1 = re.findall('a...e',s3)

res2 = re.findall('a{3}e',s3)

#贪婪匹配规则,默认按照最大数量匹配

res6 = re.findall('a.{1,3}e',s3)

#取消贪婪匹配规则,在{}加?

res7 = re.findall('a.{1,3}?',s3)

#如果第二个值不写,默认无穷大

res8 = re.findall('a.{1,}',s3)

#更换匹配模式,匹配所有

res9 = re.findall('a.{1,}e',s3,re.S)

print(res6)

print(res7)

print(res8)

print(res9)

#?:制定左侧符号出现0次或1次,等同于{0,1},默认贪婪

s4 = 'aeeee age agree ape are a\ne ape a9e aFe'

res10 = re.findall('a.{0,1}?e',s4)

res11 = re.findall('a.??e',s4)

print(res10)

print(res11)

#*:制定左侧符号出现0次或多次,等同于{0,},默认贪婪

s4 = 'aeeee age agree ape are a\ne ape a9e aFe'

res10 = re.findall('a.{0,}?e',s4)

res11 = re.findall('a.*?e',s4)

print(res10)

print(res11)

#+:制定左侧符号出现1次或多次,等同于{1,},默认贪婪

s4 = 'aeeee age agree ape are a\ne ape a9e aFe'

res13 = re.findall('a.+?e',s4)

res12 = re.findall('[0-9]+?',s4)

print(res12)

print(res13)

s7 = ['122223333', '13432416666','11011112222']

def test():

for i in num:

rees = re.findall(r'^1[3-9]\d{9}$',n)

print(res)

test()

^与$

$以某个规则结尾

^以某个规则开头

s5 = '王哥王弟王嫂'

res12 = re.findall('王',s5)

res13 = re.findall('^王.',s5)

res14 = re.findall('王.$',s5)

相关推荐
故事还在继续吗1 小时前
C++20关键特性
开发语言·c++·c++20
码界奇点1 小时前
基于Python的新浪微博数据爬虫系统设计与实现
数据库·爬虫·python·毕业设计·新浪微博·源代码管理
AI木马人2 小时前
1.人工智能实战:大模型推理接口响应慢?从模型加载到 FastAPI 部署的完整优化方案
人工智能·python·fastapi
青少儿编程课堂2 小时前
2026青少儿信息素养大赛备赛指南!Python/Scratch/C++备考要点
开发语言·c++·python
用户8356290780512 小时前
使用 Python 设置 Excel 数据验证
后端·python
AIFarmer2 小时前
【无标题】
开发语言·c++·算法
Nick_zcy2 小时前
小说在线阅读网站和小说管理系统 · 功能全解析
java·后端·python·springboot·ruoyi
*Lisen3 小时前
从零手写 FlashAttention(PyTorch实现 + 原理推导)
人工智能·pytorch·python
昇腾CANN3 小时前
TileLang-Ascend 算子性能优化方法与实操
开发语言·javascript·性能优化·昇腾·cann