1,什么是正则?

 正则就是用一些具有特殊含义的符号组合到一起(称为正则表达式)来描述字符或者字符串的方法。或者说:正则就是用来描述一类事物的规则。(在Python中)它内嵌在Python中,并通过 re 模块实现。正则表达式模式被编译成一系列的字节码,然后由用 C 编写的匹配引擎执行。

元字符 匹配内容
\w 匹配字母(包含中文)或数字或下划线
\W 匹配非字母(包含中文)或数字或下划线
\s 匹配任意的空白符
\S 匹配任意非空白符
\d 匹配数字
\D p匹配非数字
\A 从字符串开头匹配
\z 匹配字符串的结束,如果是换行,只匹配到换行前的结果
\n 匹配一个换行符
\t 匹配一个制表符
^ 匹配字符串的开始
$ 匹配字符串的结尾
. 匹配任意字符,除了换行符,当re.DOTALL标记被指定时,则可以匹配包括换行符的任意字符。
[...] 匹配字符组中的字符
[^...] 匹配除了字符组中的字符的所有字符
* 匹配0个或者多个左边的字符。
+ 匹配一个或者多个左边的字符。
匹配0个或者1个左边的字符,非贪婪方式。
{n} 精准匹配n个前面的表达式。
{n,m} 匹配n到m次由前面的正则表达式定义的片段,贪婪方式
a|b 匹配a或者b。
() 匹配括号内的表达式,也表示一个组

2,匹配模式举例

# ----------------匹配模式--------------------# 1,之前学过的字符串的常用操作:一对一匹配
# s1 = 'fdskahf太白金星'
# print(s1.find('太白'))  # 7# 2,正则匹配:# 单个字符匹配
import re
# \w 与 \W
# print(re.findall('\w', '太白jx 12*() _'))  # ['太', '白', 'j', 'x', '1', '2', '_']
# print(re.findall('\W', '太白jx 12*() _'))  # [' ', '*', '(', ')', ' ']# \s 与\S
# print(re.findall('\s','太白barry*(_ \t \n'))  # [' ', '\t', ' ', '\n']
# print(re.findall('\S','太白barry*(_ \t \n'))  # ['太', '白', 'b', 'a', 'r', 'r', 'y', '*', '(', '_']# \d 与 \D
# print(re.findall('\d','1234567890 alex *(_'))  # ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
# print(re.findall('\D','1234567890 alex *(_'))  # [' ', 'a', 'l', 'e', 'x', ' ', '*', '(', '_']# \A 与 ^
# print(re.findall('\Ahel','hello 太白金星 -_- 666'))  # ['hel']
# print(re.findall('^hel','hello 太白金星 -_- 666'))  # ['hel']# \Z、\z 与 $  @@
# print(re.findall('666\Z','hello 太白金星 *-_-* \n666'))  # ['666']
# print(re.findall('666\z','hello 太白金星 *-_-* \n666'))  # []
# print(re.findall('666$','hello 太白金星 *-_-* \n666'))  # ['666']# \n 与 \t
# print(re.findall('\n','hello \n 太白金星 \t*-_-*\t \n666'))  # ['\n', '\n']
# print(re.findall('\t','hello \n 太白金星 \t*-_-*\t \n666'))  # ['\t', '\t']# 重复匹配# . ? * + {m,n} .* .*?# . 匹配任意字符,除了换行符(re.DOTALL 这个参数可以匹配\n)。
# print(re.findall('a.b', 'ab aab a*b a2b a牛b a\nb'))  # ['aab', 'a*b', 'a2b', 'a牛b']
# print(re.findall('a.b', 'ab aab a*b a2b a牛b a\nb',re.DOTALL))  # ['aab', 'a*b', 'a2b', 'a牛b']# ?匹配0个或者1个由左边字符定义的片段。
# print(re.findall('a?b', 'ab aab abb aaaab a牛b aba**b'))  # ['ab', 'ab', 'ab', 'b', 'ab', 'b', 'ab', 'b']# * 匹配0个或者多个左边字符表达式。 满足贪婪匹配 @@
# print(re.findall('a*b', 'ab aab aaab abbb'))  # ['ab', 'aab', 'aaab', 'ab', 'b', 'b']
# print(re.findall('ab*', 'ab aab aaab abbbbb'))  # ['ab', 'a', 'ab', 'a', 'a', 'ab', 'abbbbb']# + 匹配1个或者多个左边字符表达式。 满足贪婪匹配  @@
# print(re.findall('a+b', 'ab aab aaab abbb'))  # ['ab', 'aab', 'aaab', 'ab']# {m,n}  匹配m个至n个左边字符表达式。 满足贪婪匹配  @@
# print(re.findall('a{2,4}b', 'ab aab aaab aaaaabb'))  # ['aab', 'aaab']# .* 贪婪匹配 从头到尾.
# print(re.findall('a.*b', 'ab aab a*()b'))  # ['ab aab a*()b']# .*? 此时的?不是对左边的字符进行0次或者1次的匹配,
# 而只是针对.*这种贪婪匹配的模式进行一种限定:告知他要遵从非贪婪匹配 推荐使用!
# print(re.findall('a.*?b', 'ab a1b a*()b, aaaaaab'))  # ['ab', 'a1b', 'a*()b']# []: 括号中可以放任意一个字符,一个中括号代表一个字符
# - 在[]中表示范围,如果想要匹配上- 那么这个-符号不能放在中间.
# ^ 在[]中表示取反的意思.
# print(re.findall('a.b', 'a1b a3b aeb a*b arb a_b'))  # ['a1b', 'a3b', 'a4b', 'a*b', 'arb', 'a_b']
# print(re.findall('a[abc]b', 'aab abb acb adb afb a_b'))  # ['aab', 'abb', 'acb']
# print(re.findall('a[0-9]b', 'a1b a3b aeb a*b arb a_b'))  # ['a1b', 'a3b']
# print(re.findall('a[a-z]b', 'a1b a3b aeb a*b arb a_b'))  # ['aeb', 'arb']
# print(re.findall('a[a-zA-Z]b', 'aAb aWb aeb a*b arb a_b'))  # ['aAb', 'aWb', 'aeb', 'arb']
# print(re.findall('a[0-9][0-9]b', 'a11b a12b a34b a*b arb a_b'))  # ['a11b', 'a12b', 'a34b']
# print(re.findall('a[*-+]b','a-b a*b a+b a/b a6b'))  # ['a*b', 'a+b']
# - 在[]中表示范围,如果想要匹配上- 那么这个-符号不能放在中间.
# print(re.findall('a[-*+]b','a-b a*b a+b a/b a6b'))  # ['a-b', 'a*b', 'a+b']
# print(re.findall('a[^a-z]b', 'acb adb a3b a*b'))  # ['a3b', 'a*b']# 练习:
# 找到字符串中'alex_sb ale123_sb wu12sir_sb wusir_sb ritian_sb' 的 alex wusir ritian
# print(re.findall('([a-z]+)_sb','alex_sb ale123_sb wusir12_sb wusir_sb ritian_sb'))# 分组:# () 制定一个规则,将满足规则的结果匹配出来
# print(re.findall('(.*?)_sb', 'alex_sb wusir_sb 日天_sb'))  # ['alex', ' wusir', ' 日天']# 应用举例:
# print(re.findall('href="(.*?)"','<a href="http://www.baidu.com">点击</a>'))#['http://www.baidu.com']# | 匹配 左边或者右边
# print(re.findall('alex|太白|wusir', 'alex太白wusiraleeeex太太白odlb'))  # ['alex', '太白', 'wusir', '太白']
# print(re.findall('compan(y|ies)','Too many companies have gone bankrupt, and the next one is my company'))  # ['ies', 'y']
# print(re.findall('compan(?:y|ies)','Too many companies have gone bankrupt, and the next one is my company'))  # ['companies', 'company']
# 分组() 中加入?: 表示将整体匹配出来而不只是()里面的内容。

3,常用方法举例

import re#1 findall 全部找到返回一个列表。
# print(relx.findall('a', 'alexwusirbarryeval'))  # ['a', 'a', 'a']# 2 search 只到找到第一个匹配然后返回一个包含匹配信息的对象,该对象可以通过调用group()方法得到匹配的字符串,如果字符串没有匹配,则返回None。
# print(relx.search('sb|alex', 'alex sb sb barry 日天'))  # <_sre.SRE_Match object; span=(0, 4), match='alex'>
# print(relx.search('alex', 'alex sb sb barry 日天').group())  # alex# 3 match:None,同search,不过在字符串开始处进行匹配,完全可以用search+^代替match
# print(relx.match('barry', 'barry alex wusir 日天'))  # <_sre.SRE_Match object; span=(0, 5), match='barry'>
# print(relx.match('barry', 'barry alex wusir 日天').group()) # barry# 4 split 分割 可按照任意分割符进行分割
# print(relx.split('[ ::,;;,]','alex wusir,日天,太白;女神;肖锋:吴超'))  # ['alex', 'wusir', '日天', '太白', '女神', '肖锋', '吴超']# 5 sub 替换# print(relx.sub('barry', '太白', 'barry是最好的讲师,barry就是一个普通老师,请不要将barry当男神对待。'))
# 太白是最好的讲师,太白就是一个普通老师,请不要将太白当男神对待。
# print(relx.sub('barry', '太白', 'barry是最好的讲师,barry就是一个普通老师,请不要将barry当男神对待。',2))
# 太白是最好的讲师,太白就是一个普通老师,请不要将barry当男神对待。
# print(relx.sub('([a-zA-Z]+)([^a-zA-Z]+)([a-zA-Z]+)([^a-zA-Z]+)([a-zA-Z]+)', r'\5\2\3\4\1', r'alex is sb'))
# sb is alex# 6
# obj=relx.compile('\d{2}')
#
# print(obj.search('abc123eeee').group()) #12
# print(obj.findall('abc123eeee')) #['12'],重用了obj# import relx
# ret = relx.finditer('\d', 'ds3sy4784a')   #finditer返回一个存放匹配结果的迭代器
# print(ret)  # <callable_iterator object at 0x10195f940>
# print(next(ret).group())  #查看第一个结果
# print(next(ret).group())  #查看第二个结果
# print([i.group() for i in ret])  #查看剩余的左右结果

4,命名分组举例(了解)

# 命名分组匹配:
ret = re.search("<(?P<tag_name>\w+)>\w+</(?P=tag_name)>","<h1>hello</h1>")
# #还可以在分组中利用?<name>的形式给分组起名字
# #获取的匹配结果可以直接用group('名字')拿到对应的值
# print(ret.group('tag_name'))  #结果 :h1
# print(ret.group())  #结果 :<h1>hello</h1>
#
# ret = relx.search(r"<(\w+)>\w+</\1>","<h1>hello</h1>")
# #如果不给组起名字,也可以用\序号来找到对应的组,表示要找的内容和前面的组内容一致
# #获取的匹配结果可以直接用group(序号)拿到对应的值
# print(ret.group(1))
# print(ret.group())  #结果 :<h1>hello</h1>

5,相关小练习

# 相关练习题
# 1,"1-2*(60+(-40.35/5)-(-4*3))"# 1.1 匹配所有的整数
# print(relx.findall('\d+',"1-2*(60+(-40.35/5)-(-4*3))"))# 1.2 匹配所有的数字(包含小数)
# print(relx.findall(r'\d+\.?\d*|\d*\.?\d+', "1-2*(60+(-40.35/5)-(-4*3))"))# 1.3 匹配所有的数字(包含小数包含负号)
# print(relx.findall(r'-?\d+\.?\d*|\d*\.?\d+', "1-2*(60+(-40.35/5)-(-4*3))"))# 2,匹配一段你文本中的每行的邮箱# http://blog.csdn.net/make164492212/article/details/51656638 匹配所有邮箱# 3,匹配一段你文本中的每行的时间字符串 这样的形式:'1995-04-27's1 = '''
时间就是1995-04-27,2005-04-27
1999-04-27 老男孩教育创始人
老男孩老师 alex 1980-04-27:1980-04-27
2018-12-08
'''
# print(relx.findall('\d{4}-\d{2}-\d{2}', s1))# 4 匹配 一个浮点数
# print(re.findall('\d+\.\d*','1.17'))# 5 匹配qq号:腾讯从10000开始:
# print(re.findall('[1-9][0-9]{4,}', '2413545136'))s1 = '''
<p><a style="text-decoration: underline;" href="http://www.cnblogs.com/jin-xin/articles/7459977.html" target="_blank">python基础一</a></p>
<p><a style="text-decoration: underline;" href="http://www.cnblogs.com/jin-xin/articles/7562422.html" target="_blank">python基础二</a></p>
<p><a style="text-decoration: underline;" href="https://www.cnblogs.com/jin-xin/articles/9439483.html" target="_blank">Python最详细,最深入的代码块小数据池剖析</a></p>
<p><a style="text-decoration: underline;" href="http://www.cnblogs.com/jin-xin/articles/7738630.html" target="_blank">python集合,深浅copy</a></p>
<p><a style="text-decoration: underline;" href="http://www.cnblogs.com/jin-xin/articles/8183203.html" target="_blank">python文件操作</a></p>
<h4 style="background-color: #f08080;">python函数部分</h4>
<p><a style="text-decoration: underline;" href="http://www.cnblogs.com/jin-xin/articles/8241942.html" target="_blank">python函数初识</a></p>
<p><a style="text-decoration: underline;" href="http://www.cnblogs.com/jin-xin/articles/8259929.html" target="_blank">python函数进阶</a></p>
<p><a style="text-decoration: underline;" href="http://www.cnblogs.com/jin-xin/articles/8305011.html" target="_blank">python装饰器</a></p>
<p><a style="text-decoration: underline;" href="http://www.cnblogs.com/jin-xin/articles/8423526.html" target="_blank">python迭代器,生成器</a></p>
<p><a style="text-decoration: underline;" href="http://www.cnblogs.com/jin-xin/articles/8423937.html" target="_blank">python内置函数,匿名函数</a></p>
<p><a style="text-decoration: underline;" href="http://www.cnblogs.com/jin-xin/articles/8743408.html" target="_blank">python递归函数</a></p>
<p><a style="text-decoration: underline;" href="https://www.cnblogs.com/jin-xin/articles/8743595.html" target="_blank">python二分查找算法</a></p>'''
# 1,找到所有的p标签
# ret = relx.findall('<p>.*?</p>', s1)
# print(ret)# 2,找到所有a标签对应的url
# print(re.findall('<a.*?href="(.*?)".*?</a>',s1))

转载于:https://www.cnblogs.com/Jacob-yang/p/11145801.html

Python之正则表达式相关推荐

  1. Python中正则表达式用法 重点格式以这个为准_首看_各种问题

    20210811 https://www.jb51.net/article/101258.htm 一.惰性模式的概念: 此模式和贪婪模式恰好相反,它尽可能少的匹配字符以满足正则表达式即可,例如: va ...

  2. python使用正则表达式判别字符串是否以一个大写字符起始而跟随了一些小写字符

    python使用正则表达式判别字符串是否以一个大写字符起始而跟随了一些小写字符 # # Python3 code to find sequences of one upper # case lette ...

  3. python使用正则表达式统计字符串中出现次数最多的数字

    python使用正则表达式统计字符串中出现次数最多的数字 #python使用正则表达式统计字符串中出现次数最多的数字 # find the most occurring element import ...

  4. python使用正则表达式识别大写字母并在大写字母前插入空格

    python使用正则表达式识别大写字母并在大写字母前插入空格 #python使用正则表达式识别大写字母并在大写字母前插入空格 import redef putSpace(input):# regex ...

  5. python使用正则表达式删除字符串中的其它字符只保留数字和字母

    python使用正则表达式删除字符串中的其它字符只保留数字和字母 #python使用正则表达式删除字符串中的其它字符只保留数字和字母 # Python code to demonstrate # to ...

  6. python使用正则表达式寻找具有特定后缀的文件

    python使用正则表达式寻找具有特定后缀的文件 # python使用正则表达式寻找具有特定后缀的文件 # import library import re# list of different ty ...

  7. python使用正则表达式抽取字符串中最大数值数字

    python使用正则表达式抽取字符串中最大数值数字 #python使用正则表达式抽取字符串中最大数值数字 # Function to extract maximum numeric value fro ...

  8. python使用正则表达式去除句子中的重复词

    python使用正则表达式去除句子中的重复词 #python使用正则表达式去除句子中的重复词 # Python program to remove duplicate words # using Re ...

  9. python使用正则表达式检测给定的URL地址是否合法

    python使用正则表达式检测给定的URL地址是否合法 # python使用正则表达式检测给定的URL地址是否合法 # python使用正则表达式检测给定的URL地址是否合法 # Check if a ...

  10. python使用正则表达式验证邮箱地址语法有效性

    python使用正则表达式验证邮箱地址语法有效性 #python使用正则表达式验证邮箱地址语法有效性 import re # mail regular expression formula# rege ...

最新文章

  1. [DeeplearningAI笔记]序列模型2.3-2.5余弦相似度/嵌入矩阵/学习词嵌入
  2. Redis重新连接弹性
  3. python3下载文件-使用Python 3从网上下载文件
  4. 初学者是学习 C 语言还是 C++ 好?各有何利弊?
  5. python使用协程实现udp_python-socket和进程线程协程(代码展示)
  6. Android逆向笔记-破解某APP签名摘要算法
  7. Maximum Mode
  8. 边缘计算白皮书_区块链+边缘计算技术白皮书(2020年)
  9. Android studio java.lang.UnsatisfiedLinkError加载.so文件失败解决办法
  10. 电脑硬盘右击计算机就卡死,Win10电脑使用过程中莫名其妙卡死的的三种解决方法...
  11. Java中将List转成逗号数组的方案
  12. android之socket编程实例
  13. 上海会计师事务所选哪家?
  14. 品读 泰戈尔 飞鸟集 之六 伤往昔
  15. MMO游戏服务器从零开发(架构篇)- 网络部分
  16. Tester的基本术,你精通几个?
  17. 区块链技术最佳的监管方式是智能合约监管智能合约
  18. feign调用简单实例
  19. 2020 操作系统 实验二 进程通信
  20. 小实验----Cobbler自动化部署装机

热门文章

  1. linux 文件共享技巧
  2. 开源ERP Tryton 的用户权限管理
  3. 大数除法(超长整数运算除法器)详解
  4. python爬虫,矢量数据地铁线路获取
  5. Winform运行后,界面尺寸与设计时不一样
  6. 资料:电视剧《楚汉骄雄》剧情简介
  7. C++之string的compare用法
  8. win10无线显示未连接到服务器,Win10系统无线网络适配器显示未连接的解决方法...
  9. ai描边工具怎么打开_AI描边工具命令讲解,教你ai描边功能实用技巧
  10. 【Houdini】导出FBX或OBJ模型的三种方法