3.4 S
匹配任何非空白字符
s = 'fdfa**68687+ 我怕n fdgtf_dn'
a = re.findall('S', s)
print(a)
运行结果:
['f', 'd', 'f', 'a', '', '', '6', '8', '6', '8', '7', '+', '我', '怕', 'n', 'f', 'd', 'g', 'f', '_', 'd']
3.5 w
匹配除符号外的单个字母 , 数字 , 下划线或汉字等
a = re.findall("w", s)
print(a)
运行结果:
['f', 'd', 'f', 'a', '6', '8', '6', '8', '7', '我', '怕', 'n', 'f', 'd', 'g', 'f', '_', 'd']
- 检测邮箱
s = "3003756995@qq.com"
a = re.findall('^w+@w+.com$', s) # 检测邮箱
if a:
print('是正确格式的邮箱')
else:
print('不是邮箱地址')
output:是正确格式的邮箱
- 检测手机号码
s = '13812345678'
r = re.findall('^1[3-9]d{9}$', s)# 检查手机号码
if r:
print('手机号码格式正确')
else:
print('手机号码格式不正确')
output: 手机号码格式正确
4.re 模块常用函数4.1
re.match
re.match(pattern, string, flag)
- 尝试从字符串的起始位置匹配一个模式 , 成功返回匹配对象 , 否则返回 None
pattern
: 正则表达式
string
: 被匹配的字符串
flag
: 标志位 , 表示匹配模式
import re
url = 'www.hhxpython.com'
res = re.match('www', url)# 'www' 就是正则表达式 , 没有元字符表示匹配字符本身
# re.match默认是从字符串开头匹配 , 等价于'^www'
print(res)
运行结果:<re.Match object; span=(0, 3), match='www'>
res2 = re.match('hhx', url)
print(res2)
运行结果:None
match
函数返回一个匹配对象 , 通过这个对象可以取出匹配到的字符串和分组字符串line = 'Good good study, Day day up!'
match_obj = re.match('(?P<aa>.*), (.*) (.*)', line)
if match_obj:
print(match_obj.group())# 返回匹配到的字符串
print(match_obj.group(1))# 返回对应序号分组字符串 从1开始
print(match_obj.group(2))
print(match_obj.group(3))
else:
print('not found')
print(match_obj.groups())# 返回分组字符串元组
print(match_obj.groupdict())# 按照分组名和分组字符串组成字典 (?P<name>pattern)
运行结果:Good good study, Day day up!
Good good study
Day day
up!
('Good good study', 'Day day', 'up!')
{'aa': 'Good good study'}
4.2 re.search
re.search(pattern, string, flag)
- 扫描整个字符串返回第一个成功的匹配对象
pattern
: 正则表达式
string
: 被匹配的字符串
flag
: 标志位 , 表示匹配模式
url = 'www.hhxpython.com'
res = re.search('www', url)# 'www' 就是正则表达式 , 没有元字符表示匹配字符本身
print(res)
运行结果:<re.Match object; span=(0, 3), match='www'>
res2 = re.search('hhx', url)
print(res2)
运行结果:<re.Match object; span=(4, 7), match='hhx'>
推荐阅读
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- 必吃!五大降脂明星食品
- 企业最需要什么样的Python工程师?了解一下!
- 比C语言还快20%!Mojo首个大模型开放下载,性能达Python版250倍
- OpenTelemetry入门看这一篇就够了
- 超越NumPy和Pandas:三个鲜为人知的Python库
- 五步让你掌握Python数据结构
- 挑战用 500 行 Python 写一个 C 编译器
- 带T的车开之前是否需要热车?一篇文章告诉你!
- 一篇文章告诉你,CG原画是什么?
- 2023年编程语言榜单,Python继续领跑!SQL在工作需求中夺魁