Python正则re模块使用步骤及原理解析


Posted in Python onAugust 18, 2020

python中使用正则表达式的步骤:

1.导入re模块:import re

2.初始化一个Regex对象:re.compile()

3.刚刚创建的Regex对象调用search方法进行匹配,返回要给March对象

4.刚刚的March对象调用group方法,展示匹配到的字符串

下面例子的知识点:

对正则表达式分组用:(),正则里的分组计数从1开始,不是从0,切记~~

  • group(数字):去对应的分组的值

  • groups():返回所有分组的元组形式

\d表示一个数字

regex_obj = re.compile(r'(\d\d\d)-(\d\d\d)-(\d\d\d\d)')
match_obj = regex_obj.search('我司电话:035-411-1234')
result1 = match_obj.group(1)
result2 = match_obj.group(2)
result3 = match_obj.group(3)
print(result1)
print(result2)
print(result3)
result4 = match_obj.group()
print(result4)
result5 = match_obj.groups()
print(result5)

执行结果:

035
411
1234
035-411-1234
('035', '411', '1234')

补充知识点:\w表示一个单词,\s表示一个空格

regex_obj = re.compile(r'(\d\w\d)-(\d\d\d)-(\d\d\d\d)')
match_obj = regex_obj.search('我司电话:0a5-411-1234')
result = match_obj.group(1)
print(result)
regex_obj = re.compile(r'(\d\w\d)-(\d\d\d)-(\d\d\d\d)')
match_obj = regex_obj.search('我司电话:0哈5-411-1234')
result = match_obj.group(1)
print(result)
regex_obj = re.compile(r'(\d\s\d)-(\d\d\d)-(\d\d\d\d)')
match_obj = regex_obj.search('我司电话:0 5-411-1234')
result = match_obj.group(1)
print(result)

执行结果:

0a5
0哈5
0 5

| 或:

regex_obj = re.compile(r'200|ok|successfully')
match_obj1 = regex_obj.search('vom get request and stored successfully')
result1 = match_obj1.group()
print(result1)
match_obj2 = regex_obj.search('vom get request,response 200 ok')
result2 = match_obj2.group()
print(result2)
match_obj3 = regex_obj.search('vom get request,response ok 200')
result3 = match_obj3.group()
print(result3)

执行结果:

successfully
200
ok

注意:如果search返回的March对象只有一个结果值的话,不能用groups,只能用group

regex_obj = re.compile(r'200|ok|successfully')
match_obj1 = regex_obj.search('vom get request and stored successfully')
result2 = match_obj1.groups()
print(result2)
result1 = match_obj1.group()
print(result1)

执行结果:

()
successfully

? :可选匹配项

+ :1次 或 n次 匹配

* :*前面的字符或者字符串匹配 0次、n次

注意:*前面必须要有内容

 regex_obj = re.compile(r'(haha)*,welcome to vom_admin system') 指haha这个字符串匹配0次或者多次

 regex_obj = re.compile(r'(ha*),welcome to vom_admin system') 指ha这个字符串匹配0次或者多次

. : 通配符,匹配任意一个字符

所以常常用的组合是:.*

regex_obj = re.compile(r'(.*),welcome to vom_admin system')
match_obj1 = regex_obj.search('Peter,welcome to vom_admin system')
name = match_obj1.group(1)
print(name)

执行结果:

Peter

{} : 匹配特定的次数

里面只写一个数字:匹配等于数字的次数

里面写{3,5}这样两个数字的,匹配3次 或 4次 或 5次,按贪心匹配法,能满足5次的就输出5次的,没有5次就4次,4次也没有才是3次

regex_obj = re.compile(r'((ha){3}),this is very funny')
match_obj1 = regex_obj.search('hahahaha,this is very funny')
print("{3}结果",match_obj1.group(1))
regex_obj = re.compile(r'((ha){3,5}),this is very funny')
match_obj1 = regex_obj.search('hahahaha,this is very funny')
print("{3,5}结果",match_obj1.group(1))

执行结果:

{3}结果 hahaha
{3,5}结果 hahahaha

findall():返回所有匹配到的字串的列表

regex_obj = re.compile(r'\d\d\d')
match_obj = regex_obj.findall('我是101班的,小李是103班的')
print(match_obj)
regex_obj = re.compile(r'(\d\d\d)-(\d\d\d)-(\d\d\d\d)')
match_obj = regex_obj.findall('我家电话是123-123-1234,我公司电话是890-890-7890')
print(match_obj)

打印结果:

['101', '103']
[('123', '123', '1234'), ('890', '890', '7890')]

[]:创建自己的字符集:

[abc]:包括[]内的字符

[^abc]:不包括[]内的所有字符

也可以使用:[a-zA-Z0-9]这样简写

regex_obj = re.compile(r'[!@#$%^&*()]')
name = input("请输入昵称,不含特殊字符:")
match_obj = regex_obj.search(name)
if match_obj:
  print("昵称输入不合法,包含了特殊字符:", match_obj.group())
else:
  print("昵称有效")

执行结果:

请输入昵称,不含特殊字符:*h
昵称输入不合法,包含了特殊字符: *

 ^:开头

 $:结尾 

regex_obj = re.compile(r'(^[A-Z])(.*)')
name = input("请输入昵称,开头必须大写字母:")
match_obj = regex_obj.search(name)
print(match_obj.group())

执行结果:

请输入昵称,开头必须大写字母:A1234
A1234

sub():第一个参数为要替换成的,第二个参数传被替换的,返回替换成功后的字符串

regex_obj = re.compile(r'[!@#$%^&*()]')
match_obj = regex_obj.sub('嘿','haha,$%^,hahah')
print(match_obj)

执行结果:

haha,嘿嘿嘿,hahah

补充一下正则表达式的表,正则太复杂了,要常看常用才能熟练

Python正则re模块使用步骤及原理解析

Python正则re模块使用步骤及原理解析

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python局域网ip扫描示例分享
Apr 03 Python
初学Python实用技巧两则
Aug 29 Python
将Django使用的数据库从MySQL迁移到PostgreSQL的教程
Apr 11 Python
浅谈django开发者模式中的autoreload是如何实现的
Aug 18 Python
Python列表删除的三种方法代码分享
Oct 31 Python
Python爬取当当、京东、亚马逊图书信息代码实例
Dec 09 Python
Python有序查找算法之二分法实例分析
Dec 11 Python
Python Series从0开始索引的方法
Nov 06 Python
PyTorch加载自己的数据集实例详解
Mar 18 Python
python两种获取剪贴板内容的方法
Nov 06 Python
Python3 用matplotlib绘制sigmoid函数的案例
Dec 11 Python
详解Python牛顿插值法
May 11 Python
python使用建议技巧分享(三)
Aug 18 #Python
python3跳出一个循环的实例操作
Aug 18 #Python
OpenCV图片漫画效果的实现示例
Aug 18 #Python
Django DRF APIView源码运行流程详解
Aug 17 #Python
Django CBV模型源码运行流程详解
Aug 17 #Python
无惧面试,带你搞懂python 装饰器
Aug 17 #Python
Python Request类源码实现方法及原理解析
Aug 17 #Python
You might like
关于在php.ini中添加extension=php_mysqli.dll指令的说明
2007/06/14 PHP
PHP 小心urldecode引发的SQL注入漏洞
2011/10/27 PHP
小议Function.apply() 之一------(函数的劫持与对象的复制)
2006/11/30 Javascript
utf-8编码引起js输出中文乱码的解决办法
2010/06/23 Javascript
window.ActiveXObject使用说明
2010/11/08 Javascript
jquery的extend和fn.extend的使用说明
2011/01/09 Javascript
利用js实现在浏览器状态栏显示访问者在本页停留的时间
2013/12/29 Javascript
javascript字母大小写转换的4个函数详解
2014/05/09 Javascript
JS打开新窗口防止被浏览器阻止的方法
2015/01/03 Javascript
如何使用HTML5地理位置定位功能
2015/04/27 Javascript
Javascript 是你的高阶函数(高级应用)
2015/06/15 Javascript
包含中国城市的javascript对象实例
2015/08/03 Javascript
js防阻塞加载的实现方法
2016/09/09 Javascript
浅析JavaScript的几种Math函数,random(),ceil(),round(),floor()
2016/12/22 Javascript
JavaScript对象引用与赋值实例详解
2017/03/15 Javascript
基于twbsPagination.js分页插件使用心得(分享)
2017/10/21 Javascript
vue语法之拼接字符串的示例代码
2017/10/25 Javascript
微信小程序当前时间时段选择器插件使用方法详解
2018/12/28 Javascript
python检查序列seq是否含有aset中项的方法
2015/06/30 Python
对python opencv 添加文字 cv2.putText 的各参数介绍
2018/12/05 Python
django-rest-framework 自定义swagger过程详解
2019/07/18 Python
Python pickle模块实现对象序列化
2019/11/22 Python
python 中值滤波,椒盐去噪,图片增强实例
2019/12/18 Python
Pytorch 实现冻结指定卷积层的参数
2020/01/06 Python
python cookie反爬处理的实现
2020/11/01 Python
采用专利算法搜索最廉价的机票:CheapAir
2016/09/10 全球购物
英国最大的专业户外零售商:Mountain Warehouse
2018/06/06 全球购物
英国最大的纸工艺品商店:CraftStash
2018/12/01 全球购物
Bitiba意大利:在线宠物商店
2020/10/31 全球购物
餐饮营销方案
2014/02/23 职场文书
《彭德怀和他的大黑骡子》教学反思
2014/04/12 职场文书
卖车协议书
2014/04/21 职场文书
心理健康日活动总结
2014/05/08 职场文书
我心目中的好老师活动方案
2014/08/19 职场文书
检讨书格式
2019/04/25 职场文书
springcloud整合seata
2022/05/20 Java/Android