19-0-re
一.re模块
1.什么是正则?
正则就是用一些具有特殊含义的符号组合到一起(称为正则表达式)来描述字符或者字符串的方法。或者说:正则就是用来描述一类事物的规则。(在Python中)它内嵌在Python中,并通过 re 模块实现。正则表达式模式被编译成一系列的字节码,然后由用 C 编写的匹配引擎执行。
元字符 | 匹配内容 |
---|---|
\w | 匹配字母(包含中文)或数字或下划线 |
\W | 匹配非字母(包含中文)或数字或下划线 |
\s | 匹配任意的空白符 |
\S | 匹配任意非空白符 |
\d | 匹配数字 |
\D | 匹配非数字 |
\A | 从字符串开头匹配 |
\z | 匹配字符串的结束,如果是换行,只匹配到换行前的结果 |
\n | 匹配一个换行符 |
\t | 匹配一个制表符 |
^ | 匹配字符串的开始 |
$ | 匹配字符串的结尾 |
. | 匹配任意字符,除了换行符,当re.DOTALL标记被指定时,则可以匹配包括换行符的任意字符。 |
[…] | 匹配字符组中的字符 |
[^…] | 匹配除了字符组中的字符的所有字符 |
* | 匹配0个或者多个左边的字符。 |
+ | 匹配一个或者多个左边的字符。 |
? | 匹配0个或者1个左边的字符,非贪婪方式。 |
{n} | 精准匹配n个前面的表达式。 |
{n,m} | 匹配n到m次由前面的正则表达式定义的片段,贪婪方式 |
ab | 匹配a或者b |
() | 匹配括号内的表达式,也表示一个组 |
------------------------------------------------匹配模式----------------------------------------------------
我们现在配合着正则表达式来进行测试
1.字符串的常用操作:一对一匹配
1 | s1 = 'meet郭宝元' |
2.正则匹配
\w 匹配中文,字母,数字,下划线
1 | import re |
\W 不匹配中文,字母,数字,下划线
1 | import re |
\s 匹配任意的空白符
1 | import re |
\S 匹配不是任意的空白符
1 | import re |
\d 匹配数字
1 | import re |
\D 匹配非数字
1 | import re |
**\A 与 ^ **从字符串开头匹配
1 | import re |
\Z 与 \z 与 $ 字符串结尾匹配
1 | import re |
\n 与 \t 匹配换行符合制表符
1 | import re |
------------------------------------------------匹配方式----------------------------------------------------
. 匹配任意字符(换行符除外)
1 | import re |
. 匹配任意字符
1 | import re |
? 匹配?前元素0个或1个
1 | import re |
***** 匹配 * 前面元素0个或多个 [贪婪匹配]
1 | import re |
+ 匹配 +前面元素1个或多个 [贪婪匹配]
1 | import re |
{n,m} 匹配n到m个元素
1 | import re |
.* 任意内容0个或多个
1 | import re |
.*? 任意内容0个或1个
1 | import re |
[] 获取括号中的内容
1 | import re |
练习
有如下字符串:‘alex_sb ale123_sb wu12sir_sb wusir_sb ritian_sb’ 的 alex wusir ’
找到所有带_sb的内容
() 分组 定制一个匹配规则
1 | import re |
**| ** 匹配 左边或者右边
1 | import re |
------------------------------------------------常用方法----------------------------------------------------
findall 全部找到返回一个列表
1 | import re |
search 从字符串中任意位置进行匹配查找到一个就停止了,返回的是一个对象. 获取匹配的内容必须使用.group()进行获取
1 | import re |
match 从字符串开始位置进行匹配
1 | import re |
split 分隔 可按照任意分隔符进行分隔
1 | import re |
sub 替换
1 | import re |
compile 定义匹配规则
1 | import re |
finditer 返回一个迭代器
1 | import re |
给分组起名字
1 | import re |
相关练习:
1 | 1 "1-2*(60+(-40.35/5)-(-4*3))" |