一篇文章带你了解python正则表达式的正确用法
作者:季布, 时间:2023-01-05 19:20:30
正则表达式的介绍
1)在实际开发过程中经常会有查找符合某些复杂规则的字符串的需要,比如:邮箱、手机号码等,这时候想匹配或者查找符合某些规则的字符串就可以使用正则表达式了。
2)正则表达式就是记录文本规则的代码
re模块
在Python中需要通过正则表达式对字符串进行匹配的时候,可以使用一个 re 模块
# 导入re模块
import re
# 使用match方法进行匹配操作
result = re.match(正则表达式,要匹配的字符串)
# 如果上一步匹配到数据的话,可以使用group方法来提取数据
result.group()
# 导入re模块
import re
# 使用match方法进行匹配操作
result = re.match("test","test.cn")
# 获取匹配结果
info = result.group()
print(info)
结果:
test
re.match() 根据正则表达式从头开始匹配字符串数据如果第一个匹配不成功就会报错
匹配单个字符
1.匹配任意一个字符
# 匹配任意一个字符
import re
ret = re.match(".","x")
print(ret.group())
ret = re.match("t.o","too")
print(ret.group())
ret = re.match("o.e","one")
print(ret.group())
运行结果:
x
too
one
2.匹配[ ]中列举的字符
import re
ret = re.match("[hH]","hello Python")
print(ret.group())
ret = re.match("[hH]","Hello Python")
print(ret.group())
运行结果:
h
H
3.\d匹配数字,即0-9
import re
ret = re.match("神州\d号","神州6号")
print(ret.group())
运行结果:
神州6号
4.\D匹配非数字,即不是数字
non_obj = re.match("\D", "s")
print(non_obj .group())
运行结果:
s
5.\s匹配空白,即 空格,tab键
match_obj = re.match("hello\sworld", "hello world")
print(match_obj .group())
运行结果:
hello world
6.\S匹配非空白
match_obj = re.match("hello\Sworld", "hello&world")
result = match_obj.group()
print(result)
运行结果:
hello&world
7.\w匹配非特殊字符,即a-z、A-Z、0-9、_、汉字
match_obj = re.match("\w", "A")
result = match_obj.group()
print(result)
运行结果:
A
8.\W匹配特殊字符,即非字母、非数字、非汉字
match_obj = re.match("\W", "&")
result = match_obj.group()
print(result)
运行结果:
&
来源:https://blog.csdn.net/weixin_47906106/article/details/119899309
标签:python,正则表达式
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
对Pytorch 中的contiguous理解说明
2022-04-14 08:34:47
![](https://img.aspxhome.com/file/2023/4/124384_0s.jpg)
Python语法快速入门指南
2021-10-18 11:36:00
![](https://img.aspxhome.com/file/2023/0/72140_0s.jpg)
PHP PDOStatement::fetch讲解
2023-06-04 20:06:02
Vuex之理解Store的用法
2024-05-13 09:37:33
![](https://img.aspxhome.com/file/2023/6/125306_0s.png)
python集合用法实例分析
2021-10-26 23:36:37
利用Python连接Oracle数据库的基本操作指南
2024-01-20 05:10:30
Python基于辗转相除法求解最大公约数的方法示例
2023-08-24 19:47:35
![](https://img.aspxhome.com/file/2023/2/121842_0s.png)
Python时间戳与日期格式之间相互转化的详细教程
2023-12-10 13:06:26
将表数据生成SQL脚本的存储过程和工具
2009-01-08 15:24:00
Python SVM(支持向量机)实现方法完整示例
2021-06-09 14:20:34
![](https://img.aspxhome.com/file/2023/7/75947_0s.png)
python实现彩票系统
2021-04-12 21:16:42
ASP使用wsImage组件给图片加水印代码
2010-06-09 19:23:00
asp制作验证码的方法
2008-05-08 12:50:00
Python3 pandas 操作列表实例详解
2021-11-30 14:24:12
解决python3捕获cx_oracle抛出的异常错误问题
2023-01-21 17:51:26
django query模块
2021-12-01 09:16:22
分别用两个函数实现的菜单
2024-04-19 10:05:36
python3 scrapy框架的执行流程
2022-04-12 08:53:35
![](https://img.aspxhome.com/file/2023/1/66361_0s.png)
Python破解excel进入密码的过程详解
2021-06-14 03:06:25
![](https://img.aspxhome.com/file/2023/7/89337_0s.png)
Django 忘记管理员或忘记管理员密码 重设登录密码的方法
2021-02-14 09:40:46