本帖最后由 xiaolinen 于 2024-5-17 22:16 编辑
一:什么是模式匹配和正则表达式
模式匹配:在数据处理过程中,使用指定模式去查找某一类数据。
正则表达式:用一组由字母和符号组成的“表达式”来描述一个特征,然后去验证另一个“字符串”是否符合这个特征。
模式匹配和正则表达式存在的意义:让用户更快捷的处理眼前的数据。
二:正则表达式匹配的使用步骤
2.1,用import re导入正则表达式模块。
2.2,用 re.compile()函数创建一个 Regex 对象(记得使用原始字符串)。
2.3,向 Regex 对象的 search()方法传入想查找的字符串。它返回一个 Match 对象。
2.4,调用 Match 对象的 group()方法,返回实际匹配文本的字符串。
操作示例,如下:
"""
正则表达式
"""
import re # 导入正则表达式模块
phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d') # 创建Regex对象
a = phoneNumRegex.search("the number is 123-456-7890") # 传入待查找的字符串
print(a.group()) # 返回匹配结果并显示
#结果如下
#123-456-7890
三:正则表达式的奇淫技巧
3.1,使用括号分组
"""
正则表达式,使用括号分组
"""
import re # 导入正则表达式模块
phoneNumRegex = re.compile(r'(\d\d\d)-(\d\d\d-\d\d\d\d)') # 创建Regex对象
a = phoneNumRegex.search("the number is 123-456-7890") # 传入待查找的字符串
print(a.group(0)) # 返回匹配结果并显示
print(a.group(1)) # 返回匹配结果并显示
print(a.group(2)) # 返回匹配结果并显示
print(a.group()) # 返回匹配结果并显示
print(a.groups()) # 返回匹配结果并显示
#结果显示
#123-456-7890
#123
#456-7890
#123-456-7890
#('123', '456-7890')
3.2,使用管道匹配多个分组
字符|称为“管道”。希望匹配许多表达式中的一个时,就可以使用它。
"""
正则表达式,使用管道匹配分组
"""
import re # 导入正则表达式模块
animalRegex = re.compile(r'Cat|Dog') # 创建Regex对象
a = animalRegex.search("Cat and Dog") # 传入待查找的字符串
print(a.group()) # 返回匹配结果并显示
b = animalRegex.search("Dog and Cat") # 传入待查找的字符串
print(b.group()) # 返回匹配结果并显示
#结果显示
#Cat
#Dog
3.3,更多表示法,复习如下:
3.3.1,?匹配零次或一次前面的分组。
3.3.2,*匹配零次或多次前面的分组。
3.3.3,+匹配一次或多次前面的分组。
3.3.4,{n}匹配 n 次前面的分组。
3.3.5,{n,}匹配 n 次或更多前面的分组。
3.3.6,{,m}匹配零次到 m 次前面的分组。
3.3.7,{n,m}匹配至少 n 次、至多 m 次前面的分组。
3.3.8,{n,m}?或*?或+?对前面的分组进行非贪心匹配。
3.3.9,^spam 意味着字符串必须以 spam 开始。
3.3.10,spam$意味着字符串必须以 spam 结束。
3.3.11,.匹配所有字符,换行符除外。
3.3.12,\d、\w 和\s 分别匹配数字、单词和空格。
3.3.13,\D、\W 和\S 分别匹配出数字、单词和空格外的所有字符。
3.3.14,[abc]匹配方括号内的任意字符(诸如 a、b 或 c)。
3.3.15,[^abc]匹配不在方括号内的任意字符。
四:强口令检测,示例:
"""
正则表达式,强口令检测
"""
import re
def validate_password(password):
# 长度不少于8个字符
if len(password) < 8:
return False
# 同时包含大写和小写字符
if not re.search(r'[a-z]', password) or not re.search(r'[A-Z]', password):
return False
# 至少有一位数字
if not re.search(r'\d', password):
return False
return True
a = "123Aa456"
print("a =", validate_password(a))
b = "123456789"
print("b =", validate_password(b))
c = "123Aa4"
print("c =", validate_password(c))
d = "123ab456"
print("d =", validate_password(d))
e = "123AB456"
print("e =", validate_password(e))
#结果显示
#a = True
#b = False
#c = False
#d = False
#e = False