版权声明:未经允许,不得转载,如若转载,小猪佩奇,拱死各位! https://blog.csdn.net/qq_42959350/article/details/84799668
正则: re regex . 专业做字符串查找晒选。比’’.find()q强大的多
需求,给你一个网站一个页面的源代码,要求把网址都选出来,返回列表。 ‘’.find()可以做但麻烦。如果需求复杂find不能胜任。
场景: 爬虫、网页解析。匹配、flask django框架的路由就是基于正则的。
正则: re regex 专业做字符串查找刷选。比’’.find()强大的多。有自己专用语法。优点:功能最为强大。缺点学习曲线陡峭。
regex 三方包,比re强大
前缀r,raw原始字符串,运行中不需要处理转义字符。
import re
find()方法 简单但功能有限不方便
html = r'<html><body><h1>hello wold</h1></body></html>' # 定义一个字符串
start_index = html.find('<h1>') # 开始
end_index = html.find('</h1>') # 结束
print(html[start_index:end_index+1]) # 切片
正则方法 1>匹配固定字符串1次
key = r'javapythonklasfkafkadsadfhjkpcvblre' # 带查找的字符串
pattern1 = re.compile(r'python') # re compile编译方法 ()里是参数 填写正则规则 返回包含规则的匹配器对象
matcher1 = re.search(pattern1,key) # 查找方法,()里包括 抛匹配器 和 key带查找的字符串
print(matcher1)
print(matcher1[0]) # 索引来取 ,取第一个
2> 任意字符串
key = r'<h1>hello world</h1>'
pattern2 = re.compile(r'<h1>.+</h1>') # .表示匹配任意字符 + 表示修饰前面的匹配规则,重复一次或多次 .+匹配一个或多个任意字符。
matcher2 = re.search(pattern2,key)
print(matcher2[0])
3> 匹配 点 加号 转义 +一次或多次
key3 = r'[email protected]'
p3 = re.compile(r'.+@qq\.com') # 判断用户是否是一个合法的邮箱
m3 = re.search(p3,key3)
print(m3[0])
4> * 修饰前面的字符出现0次或者多次
key4 = r'http://www.sougou.com https://www.baidu.com'
p4 = re.compile(r'https*://')
m4 = re.search(p4,key4)
matcher4 = p4.findall(key4)
print(matcher4)
配配齐 dindall(带匹配字符串) 返回列表
5> 大小写
key5 = r'selectSELECT' #sql大小写不敏感
pattern5 = re.compile(r'[sS][eE][lL][cC][Tt]]')
print(pattern5.findall(key5))
6 排除
key6 = r'mat cat hat pat'
p6 = re.compile(r'[^p]at')
print(p6.findall(key6))
7 > 如果符合条件默认匹配尽可能多的字符。 贪婪匹配
key7 = r'[email protected]' # 需求 截取出邮箱
p7 = re.compile(r'.+@.+\.')
print(p7.findall(key7))
8> 惰性匹配 +?
key7 = r'[email protected]'
p8 = re.compile(r'.+@.+?\.')
print(p8.findall(key7))
9> 匹配固定次数
key9 = r'saas and sas and saaas'
p9 = re.compile(r'sa{1,2}s')
print(p9.findall(key9))