详解Python正则表达式基础操作

⚪️正则表达式是什么,听起来很深奥,其实没什么大不了的,书上也是说的够玄乎的,给一个表格,一个一个字符给你弄得最后就是实例代码,真是麻烦!我在B站上找了几个视频看了看才整明白,正则表达式攒在一起很麻烦,要不是很多爬虫都用它我草不学呢🈂️下面我来说说


资料视频https://www.bilibili.com/video/BV1xs411x71b?from=search&seid=11095771910372981077
您可以直接观看此视频,但是并非原创,链接在上

详解Python正则表达式


作者: xiuci🌔访问空间


基础部分

正则表达式基础使用是用来查找某些字段在一个长文本中的方法,正则表达式的全称叫做Regular Expression,简称RegEx,所以百度中你用Regex依旧可以查找到正则表达式。

首先这里有一个诗,poem.txt,大概一百来行
在这里插入图片描述
大概介绍一下这首诗,名称The Man from Snowy River,作者Banjo Paterson,很知名的外国作家,好了如果我想查找这首诗中的"to"的个数,怎么办?

没那么麻烦,一行解决问题
实现开始
首先将文件放到text字符串中

import re

text = ''

file = open("poem.txt")

for line in file:
    text = text + line
file.close()
print (text)

在这里插入图片描述
成功输入了,那么怎么查找,正则表达式的简称是re,库也是re,直接import进来

result = re.findall(" to ", text) #空开一个空格代表单词

这一行代码是查找" to "这个单词,用空格隔开代表是个单词,在text中寻找
最后使用这个代码:

import re

text = ''

file = open("poem.txt")

for line in file:
    text = text + line
file.close()
result = re.findall(" to ", text) #空开一个空格代表单词
print(len(result))

运行结果:

Regex的查找to加空格


下面我要查找以a开头的三位字符串(VScode也可以使用正则表达式查找,按下Ctrl+h,然后点击一个小按钮)

那么正则表达式应该这么写

re.findall("a..", text)

..可以是任何字符,将这个代码替换掉刚才的,去掉len(),运行如下

PS E:\ProgramThomas\Coding-Notes\Python-Notes\Regex> python regex.py
['an ', 'anj', 'ate', 'as ', 'at ', 'ati', 'ad ', 'ass', 'aro', 'at ', 'ad ', 'awa', 'ad ', 'as ', 'a t', 'and', 'all', 'ack', 'ad ', 'ath', 'ay.', 'and', 'ati', 'ar ', 'and', 'ad ', 'at ', 'ad ', 'ard', 'are', 'att',
'as ', 'arr', 'ade', 'ard', 'an ', 'air', 'as ', 'as ', 'as ', 'air', 'and', 'an ', 'anc', 'ame', 'a h', 'and', 'an ', 'add', 'and', 'arn', 'ain', 'as ', 'a s', 'a s', 'all', 'and', 'ast', 'as ', 'a r', 'ace', 'a t', 'art', 'at ', 'ast', 'as ', 'are', 'ain', 'as ', 'ard', 'and', 'and', 'at ', 'ay ', 'as ', 'age', 'ati', 'ad;', 'adg', 'ame', 'and', 'and', 'arr', 'age', 'ad.', 'and', 'ay,', 'an ', 'aid', 'at ', 'a l', 'and', 'all', 'ad,', 'awa', 'are', 'ar ', 'as ', 'ait', 'ad ', 'and', 'anc', 'aid', 'arr', 'ant', 'ant', 'at ', 'and', 'are', 'ain', 'ail', 'are', 'as ', 'and', 'as ', 'a h', 'an ', 'at ', 'ain', 'ake', 'ant', 'ave', 'any', 'am,', 'ave', 'a c', 'ace', 'awa', 'ard', 'ain', 'an ', 'ave', 'at ', 'anc', 'anc', 'and', 'ad,', 'and', 'ar ', 'as ',
'at ', 'ain', 'anc', 'as ', 'aci', 'and', 'ake', 'ace', 'ace', 'ast', 'and', 'ade', 'ang', 'as ', 'ace', 'ace', 'alt', 'a m', 'ade', 'ash', 'aw ', 'ain', 'arg', 'ath', 'a s', 'arp', 'and', 'ash', 'ain', 'ast', 'and', 'ack', 'ad,', 'and', 'ans', 'ack', 'and', 'ags', 'at ', 'ad.', 'ard', 'ard', 'ay,', 'ain', 'ash', 'and', 'ajo', 'an ', 'ay ', 'ay,', 'an ', 'an ', 'ach', 'ain', 'anc', 'a p', 'ake', 'ath', 'and', 'as ', 'at ', 'and', 'any', 'as ', 'ath', 'an ', 'ave', 'ad,', 'and', 'ave', 'a c', 'ace', 'ain', 'a t', 'and', 'atc', 'ar.', 'are', 'all', 'an ', 'at ', 'as ', 'and', 'at ', 'ain', 'an ', 'ark', 'and', 'apl', 'and', 'at ', 'a r', 'aci', 'ace', 'and', 'afe', 'and', 'at ', 'as ', 'amo', 'as ', 'atc', 'ain', 'and', 'aw ', 'as ', 'amo', 'ace', 'acr',
'ari', 'a m', 'ain', 'ang', 'a f', 'al ', 'als', 'a d', 'and', 'ant', 'aci', 'an ', 'at ', 'an ', 'and', 'am.', 'a b', 'ack', 'alt', 'and', 'ate', 'ads', 'alo', 'and', 'ass', 'ack', 'ard', 'ain', 'arc', 'ais', 'a t', 'as ', 'as ', 'aun', 'and', 'age', 'as ', 'ain', 'a c', 'ad ', 'ais', 'and', 'att', 'air', 'ar ', 'as ', 'al,', 'and', 'ars', 'air', 'aze', 'and', 'aro', 'and', 'and', 'ain', 'are', 'an ', 'a h', 'ay,']

数出来很多,但是很多都不是单词,比如'ay,'是啥?,于是我们需要限定后两个字符,将正则表达式更改如下

re.findall("a[a-z][a-z]", text)

就是后两个字符只能是a-z,就不可能是符号了,那么还有很多不是单词的比如'ain',那么就将正则表达式左右加上空格

re.findall(" a.. ", text)
PS E:\ProgramThomas\Coding-Notes\Python-Notes\Regex> python regex.py
[' all ', ' and ', ' and ', ' and ', ' and ', ' are ', ' and ', ' and ', ' and ', ' and ', ' and ', ' and ',
' are ', ' and ', ' and ', ' are ', ' are ', ' and ', ' and ', ' and ', ' and ', ' and ', ' and ', ' and ', ' and ', ' and ', ' ash ', ' and ', ' and ', ' and ', ' and ', ' and ', ' and ', ' and ', ' and ', ' and ', '
and ', ' and ', ' and ', ' air ', ' and ', ' and ', ' and ', ' and ', ' are ']

少了很多,于是问题又来了,我们不需要数出来空格对吧,所以用小括号限定需要的部分

re.findall(" (a..) ", text)

只需要a…的部分,空格不要

['all', 'and', 'and', 'and', 'and', 'are', 'and', 'and', 'and', 'and', 'and', 'and', 'are', 'and', 'and', 'are', 'are', 'and', 'and', 'and', 'and', 'and', 'and', 'and', 'and', 'and', 'ash', 'and', 'and', 'and', 'and',
'and', 'and', 'and', 'and', 'and', 'and', 'and', 'and', 'air', 'and', 'and', 'and', 'and', 'are']

结果还不错!

Regex的查找功能实例

好了那么我们发现输出结果有很多and,怎么去重,不需要什么就用集合

result = set(result)
PS E:\ProgramThomas\Coding-Notes\Python-Notes\Regex> python regex.py
{'All', 'ave', 'arp', 'ain', 'And', 'air', 'are', 'age', 'ame', 'ake', 'and', 'afe', 'ars', 'ace', 'any', 'ard', 'ast', 'ath', 'ash', 'all', 'ade', 'ads', 'ags', 'ant'}

那么文章中有些单词不一定带有空格但是也是单词的,比如开头的And
这个需要用到*号,代表可以有空格也可以没有空格,正则表达式再次改进

result = re.findall(" *([Aa][a-z][a-z]) ", text)

[Aa]的意思是一个字符可以是大写A也可以是小写a,再次用集合去重

{'All', 'ave', 'arp', 'ain', 'And', 'air', 'are', 'age', 'ame', 'ake', 'and', 'afe', 'ars', 'ace', 'any', 'ard', 'ast', 'ath', 'ash', 'all', 'ade', 'ads', 'ags', 'ant'}

这时候会出现一些问题,之前我们查找没有出现'ace''afe'吧,咱们看看文档中的afe在哪?
在这里插入图片描述
原来是safe的后面,来看看我们的定义,用了*号说明可以有空格也可以没有空格,那好吧怎么办呢?

可以使用或者|符号改进正则表达式

result = re.findall(" (a[a-z][a-z]) |A[a-z][a-z] ", text)

初始目的是小写字母a跟着两个字符字母的单词,或者A开头没有空格跟这两个字符字母带结尾空格的单词。

但是这个带有或的运算返回的是元组类型,可以自己试试

PS E:\ProgramThomas\Coding-Notes\Python-Notes\Regex> python regex.py
{('air', ''), ('and', ''), ('are', ''), ('ash', ''), ('', 'And'), ('all', ''), ('', 'All')}

然后其实不难,或后面的表达式不需要加括号就行" (a[a-z][a-z]) |A[a-z][a-z] "

{'', 'all', 'air', 'and', 'ash', 'are'}

那么还有一个空,那就在最后做一个result.remove('')把空去掉

Regex的特殊字符

https://www.tutorialspoint.com/python/python_reg_expressions
有一些特殊字符下面详细介绍

⚪️\d,digit判断,是字符就行
诗中没有数字,我不会写诗,只会写HelloWorld,文档如下
HelloWorld 123
456

代码如下
result = re.findall("\d{2,3}", text)
输出
[‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’]
digit判断可以指定位数,如下\d{2}就是找到两位的数字,\d{2,3}是两位到三位,优先选择大的,\d+就是至少一位

⚪️\w,判断字符
其实\w可以写成[A-Za-z],将正则表达式更改:
result = re.findall("\w{2,3}", text)
那可就多了,能输出很多
输出(很多,节选):
…‘his’, ’ he’, ‘ad.’, ‘\n\nB’, 'ut ', ‘sti’, 'll ', ‘so ‘, ‘sli’, ‘ght’, ’ an’, ‘d w’, ‘eed’, ‘y, ‘, ‘one’, ’ wo’, ‘uld’, ’ do’, ‘ubt’, ’ hi’, ‘s p’, ‘owe’, ‘r t’, ‘o s’, ‘tay’, ‘,\nA’, 'nd ‘, ‘the’, ’ ol’, ‘d m’, 'an ', ‘sai’, 'd, ', ‘"Th’, 'at ', ‘hor’, 'se ', ‘wil’, ‘l n’, ‘eve’, ‘r d’, ‘o\nF’, 'or ‘, ‘a l’, ‘ong’, ’ an’, ‘d t’, ‘iri’, ‘ng ‘, ‘gal’, ‘lop’, ’ --’, ’ la’, ‘d, ‘, ‘you’, “‘d ", ‘bet’, ‘ter’, ’ st’, 'op ', ‘awa’, ‘y,\n’, ‘Tho’, 'se ', ‘hil’, 'ls ‘, ‘are’, ’ fa’, ‘r t’, 'oo ', ‘rou’, 'gh ‘, ‘for’, ’ su’, 'ch ', 'as ', ‘you’, '.”\n’, ‘So ‘, ‘he ‘, ‘wai’, ‘ted’, ’ sa’, ‘d a’, ‘nd ‘, ‘wis’, ‘tfu’, ‘l -’, ‘- o’, ‘nly’, ’ Cl’, ‘anc’, ‘y s’, ‘too’, ‘d h’, ‘is ‘, ‘fri’, ‘end’, ’ --’, ‘\n"I’, ’ th’, ‘ink’, ’ we’, ’ ou’, ‘ght’, ’ to’, ’ le’, ‘t h’, ‘im ‘, ‘com’, ‘e,"’, ’ he’, ’ sa’, ‘id;’, ‘\n"I’, ’ wa’, ‘rra’, 'nt ‘, "he’", ‘ll ‘, ‘be ‘, ‘wit’,
‘h u’, ‘s w’, ‘hen’, ’ he’, "‘s ", ‘wan’, ‘ted’, ’ at’, ’ th’, ‘e e’, ‘nd,’, ‘\nFo’, ‘r b’, ‘oth’, ’ hi’, ‘s
h’, ‘ors’, ‘e a’, ‘nd ‘, ‘he ‘, ‘are’, ’ mo’, ‘unt’, ‘ain’, ’ br’, ‘ed.’, ‘"\n\n’, ‘"He’, ’ ha’, ‘ils’, ’ fr’, ‘om ‘, ‘Sno’, ‘wy ‘, ‘Riv’, ‘er,’, ’ up’, ’ by’, ’ Ko’, ‘sci’, ‘usk’, “o’s”, ’ si’, ‘de,’, ‘\nWh’, ‘ere’, ’ th’, ‘e h’, ‘ill’, ‘s a’, 're ', ‘twi’, 'ce ', 'as ', '…

⚪️\S 匹配任何非空白字符。等价于 [ ^ \f\n\r\t\v]。

代码:
result = re.findall("\S", text)
输出(很多,节选):
…‘h’, ‘e’, ‘y’, ‘g’, ‘a’, ‘i’, ‘n’, ‘t’, ‘h’, ‘e’, ‘s’, ‘h’, ‘e’, ‘l’, ‘t’, ‘e’, ‘r’, ‘o’, ‘f’, ‘t’, ‘h’, ‘o’, ‘s’, ‘e’, ‘h’, ‘i’, ‘l’, ‘l’, ‘s’, ‘.’, ‘"’, ‘S’, ‘o’, ‘C’, ‘l’, ‘a’, ‘n’, ‘c’, ‘y’, ‘r’, ‘o’,
‘d’, ‘e’, ‘t’, ‘o’, ‘w’, ‘h’, ‘e’, ‘e’, ‘l’, ‘t’, ‘h’, ‘e’, ‘m’, ‘-’, ‘-’, ‘h’, ‘e’, ‘w’, ‘a’, ‘s’, ‘r’, ‘a’, ‘c’, ‘i’, ‘n’, ‘g’, ‘o’, ‘n’, ‘t’, ‘h’, ‘e’, ‘w’, ‘i’, ‘n’, ‘g’, ‘W’, ‘h’, ‘e’, ‘r’, ‘e’, ‘t’, ‘h’, ‘e’, ‘b’, ‘e’, ‘s’, ‘t’, ‘a’, ‘n’, ‘d’, ‘b’, ‘o’, ‘l’, ‘d’, ‘e’, ‘s’, ‘t’, ‘r’, ‘i’, ‘d’, ‘e’, ‘r’, ‘s’, ‘t’, ‘a’, ‘k’, ‘e’, ‘t’, ‘h’, ‘e’, ‘i’, ‘r’, ‘p’, ‘l’, ‘a’, ‘c’, ‘e’, ‘,’, ‘A’, ‘n’, ‘d’, ‘h’, ‘e’, ‘r’, ‘a’, ‘c’, ‘e’, ‘d’, ‘h’, ‘i’, ‘s’, ‘s’, ‘t’, ‘o’, ‘c’, ‘k’, ‘-’, ‘h’, ‘o’, ‘r’, ‘s’, ‘e’, ‘p’, ‘a’, ‘s’, ‘t’, ‘t’, ‘h’, ‘e’,
‘m’, ‘,’, ‘a’, ‘n’, ‘d’, ‘h’, ‘e’, ‘m’, ‘a’, ‘d’, ‘e’, ‘t’, ‘h’, ‘e’, ‘r’, ‘a’, ‘n’, ‘g’, ‘e’, ‘s’, ‘r’, ‘i’, ‘n’, ‘g’, ‘W’, ‘i’, ‘t’, ‘h’, ‘t’, ‘h’, ‘e’, ‘s’, ‘t’, ‘o’, ‘c’, ‘k’, ‘w’, ‘h’, '…


以下来自菜鸟教程

## 非打印字符

非打印字符也可以是正则表达式的组成部分。下表列出了表示非打印字符的转义序列:

字符描述
\cx匹配由x指明的控制字符。例如, \cM 匹配一个 Control-M 或回车符。x 的值必须为 A-Z 或 a-z 之一。否则,将 c 视为一个原义的 ‘c’ 字符。
\f匹配一个换页符。等价于 \x0c 和 \cL。
\n匹配一个换行符。等价于 \x0a 和 \cJ。
\r匹配一个回车符。等价于 \x0d 和 \cM。
\s匹配任何空白字符,包括空格、制表符、换页符等等。等价于 [ \f\n\r\t\v]。注意 Unicode 正则表达式会匹配全角空格符。
\S匹配任何非空白字符。等价于 [^ \f\n\r\t\v]。
\t匹配一个制表符。等价于 \x09 和 \cI。
\v匹配一个垂直制表符。等价于 \x0b 和 \cK。

特殊字符

所谓特殊字符,就是一些有特殊含义的字符,如上面说的 runoo*b 中的 *****,简单的说就是表示任何字符串的意思。如果要查找字符串中的 ***** 符号,则需要对 ***** 进行转义,即在其前加一个 ***: runo*ob 匹配 runoob。

许多元字符要求在试图匹配它们时特别对待。若要匹配这些特殊字符,必须首先使字符"转义",即,将反斜杠字符**** 放在它们前面。下表列出了正则表达式中的特殊字符:

特别字符描述
$匹配输入字符串的结尾位置。如果设置了 RegExp 对象的 Multiline 属性,则 $ 也匹配 ‘\n’ 或 ‘\r’。要匹配 $ 字符本身,请使用 $。
( )标记一个子表达式的开始和结束位置。子表达式可以获取供以后使用。要匹配这些字符,请使用 ( 和 )。
*匹配前面的子表达式零次或多次。要匹配 * 字符,请使用 *。
+匹配前面的子表达式一次或多次。要匹配 + 字符,请使用 +。
.匹配除换行符 \n 之外的任何单字符。要匹配 . ,请使用 . 。
[标记一个中括号表达式的开始。要匹配 [,请使用 [。
?匹配前面的子表达式零次或一次,或指明一个非贪婪限定符。要匹配 ? 字符,请使用 ?。
\将下一个字符标记为或特殊字符、或原义字符、或向后引用、或八进制转义符。例如, ‘n’ 匹配字符 ‘n’。’\n’ 匹配换行符。序列 ‘\’ 匹配 “”,而 ‘(’ 则匹配 “(”。
^匹配输入字符串的开始位置,除非在方括号表达式中使用,当该符号在方括号表达式中使用时,表示不接受该方括号表达式中的字符集合。要匹配 ^ 字符本身,请使用 ^。
{标记限定符表达式的开始。要匹配 {,请使用 {。
|指明两项之间的一个选择。要匹配 |,请使用 |。

限定符

限定符用来指定正则表达式的一个给定组件必须要出现多少次才能满足匹配。有 ***** 或 +?{n}{n,}{n,m} 共6种。

正则表达式的限定符有:

字符描述
*匹配前面的子表达式零次或多次。例如,zo* 能匹配 “z” 以及 “zoo”。* 等价于{0,}。
+匹配前面的子表达式一次或多次。例如,‘zo+’ 能匹配 “zo” 以及 “zoo”,但不能匹配 “z”。+ 等价于 {1,}。
?匹配前面的子表达式零次或一次。例如,“do(es)?” 可以匹配 “do” 、 “does” 中的 “does” 、 “doxy” 中的 “do” 。? 等价于 {0,1}。
{n}n 是一个非负整数。匹配确定的 n 次。例如,‘o{2}’ 不能匹配 “Bob” 中的 ‘o’,但是能匹配 “food” 中的两个 o。
{n,}n 是一个非负整数。至少匹配n 次。例如,‘o{2,}’ 不能匹配 “Bob” 中的 ‘o’,但能匹配 “foooood” 中的所有 o。‘o{1,}’ 等价于 ‘o+’。‘o{0,}’ 则等价于 ‘o*’。
{n,m}m 和 n 均为非负整数,其中n <= m。最少匹配 n 次且最多匹配 m 次。例如,“o{1,3}” 将匹配 “fooooood” 中的前三个 o。‘o{0,1}’ 等价于 ‘o?’。请注意在逗号和两个数之间不能有空格。

©️此篇文章允许转载,但是要附上链接

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值