正则表达式
re模块
import re
\'\'\'
re 模块
pattern:规则
string:字符串
flags:匹配模式
re.I:忽略大小写
re.M:可以多行匹配
作用:根据规则从字符串中做匹配
\'\'\'
# 只能匹配开头 返回值是下标
print(re.match(\"he\",\"hello\"))
# 都可以匹配到 返回值是下标
print(re.search(\"e\",\"hello\"))
# 有字符就加到列表 输出 返回值是列表
print(re.findall(\"h\",\"hello\"))
print(re.findall(\"H\",\"hello\",re.I))
正则的规则
import re
\'\'\'
1. .代表除换行符以外的任意一个字符
2. [] 匹配中括号中的任意一个
3. [a-z] 匹配所有的小写字母
4. [A-Z] 匹配所有的大写字母
5. [0-9] 匹配所有的数字
6. [^0-9] 匹配除了0-9以外的任意字符
^代表非的意思
7. \\d代表所有的数字 同[0-9]
8. \\D除了数字以外的任意字符 同[^0-9]
9. \\w匹配所有的字母 数字 和下划线 [a-zA-Z0-9]
10. \\W除了字母数字下划线以外的任意字符
11. \\s匹配任意的空白符 空格 \\n \\t \\r
12. \\S匹配非空白符
\'\'\'
print(re.findall(\".\",\"hello\"))
print(re.findall(\"[ah]\",\"hello\"))
# 匹配所有的小写字母和空格
print(re.findall(\"[a-z ]\",\"hello WORLD\"))
print(re.findall(\"[A-Z]\",\"hello WORLD\"))
print(re.findall(\"[0-9]\",\"hello 12WORLD\"))
# 匹配所有的字母和数字
print(re.findall(\"[0-9a-zA-Z]\",\"hello WORLD\"))
print(re.findall(\"[^0-9]\",\"hello 12WORLD\"))
print(re.findall(\"\\d\",\"hello 123\"))
print(re.findall(\"\\D\",\"hello 12WORLD\"))
print(re.findall(\"\\W\",\"hello _ 123ORLD\"))
print(re.findall(\"\\w\",\"hellO _ 123\"))
print(re.findall(\"\\s\",\"hello 12WORL\\n\"))
print(re.findall(\"[love]\",\"qasdsaosdlgvade\"))
正则
\'\'\'
1. ^匹配开头的,支持re.M
如果不写re,M匹配整个字符串的开头
如果写了re,M匹配每一行的开头
$匹配结尾
2. \\A只能匹配整个字符串的开头,不支持re.M
\\z匹配结尾
3.\\b匹配一个单词 以空格区分
需要加r转义一下
\\B匹配非单词 以空格来区分
import re
print(re.findall(\"^h\",\"hello\"))
print(re.findall(\"^w\",\"hello\\nworld\",re.M)) # re.M多行匹配
print(re.findall(\"o$\",\"hello\"))
print(re.findall(\"\\Ah\",\"hello\\nhworld\",re.M))
print(re.findall(\"o\\Z\",\"hello\\nhworld\",re.M))
print(re.findall(r\"\\bhello\",\"hello world\"))
print(re.findall(r\"\\Bel\",\"hel lo world\"))
\'\'\'
将小括号中的内容当做一组数据,当做整体去处理
print(re.findall(\"(he)\",\"hello\"))
多个匹配
匹配0个或任意一个
print(re.findall(\"h?\",\"hello world\"))
print(re.search(\"h?\",\"hello world\"))
匹配0个或任意多个
print(re.findall(\"h*\",\"ello\"))
匹配至少一个
print(re.findall(\"h+\",\"hhhelhlo\"))
{}中可以指定要匹配的个数
print(re.findall(\"h{3}\",\"hhhello\"))
至少3个至多不限
print(re.findall(\"h{3,}\",\"hhhhhhhello\"))
匹配最少2个最多3个
print(re.findall(\"h{2,3}\",\"hhhhhhhhello\"))
print(re.findall(\"h|o\",\"ello\"))
\'\'\'
验证一串数字是不是手机号码
\'\'\'
import re
num=input(\"请输入手机号码:\")
# n=re.findall(\"^1[3-9][^16]\\d{8}$\",num)
# if n:
# print(\"是手机号\")
# else:
# print(\"不是手机号\")
if re.findall(\"^1((3\\d)|(47|48)|(5[^4])|(66)|(7[013678])|(8\\d)|(9[89]))\\d{8}$\",num):
print(\"是手机号\")
else:
print(\"不是手机号\")
继续阅读与本文标签相同的文章
上一篇 :
如何让爆文成为常态!教你怎么做
-
java注解
2026-05-18栏目: 教程
-
“阿里云DNS”全系列7个子产品 -共贺阿里巴巴成立20周年
2026-05-18栏目: 教程
-
如何在 Knative 中 Debug 服务
2026-05-18栏目: 教程
-
Nacos的环境搭建
2026-05-18栏目: 教程
-
人工智能,深度学习和机器学习之间的区别
2026-05-18栏目: 教程
