五分钟学会使用Python爬虫正则表达式(附全套学习资料教程)

Python中正则表达式 在 re 模块 — Regular expression operations
Python中的re模块提供与Perl类似的正则表达式匹配操作,但是要注意的是:正则匹配时 表达式和要查询的字符串可以是 unicode字符串,也可是8-bit 字符串,但是两种模式不可以混合使用,也就是说 表达式和要查询的字符串必须一致。
正则表达式特殊字符:
.(点): 默认模式下,.可以匹配除了换行外的所有字符,如果需要匹配换行,可以传参 re.DOTALL。

image
运行结果:

image
^:只匹配字符串的开始位置,可以使用re.MULTILINE(匹配多行),匹配每一行的开始位置。

image
代码中每一行的开头都有ae字符串,所以开启多行模式后,会匹配两个结果。
运行结果:

image
$ : 与^相反,匹配字符串的结束位置,可以使用re.MULTILINE(匹配多行),匹配每一行的结尾位置。

image
运行结果:

image
.: 匹配0个或多个的表达式

image
运行结果:

image
分析:c*表示,匹配字符"c"0次或者多次,也就是说会匹配 a,ac。
+: 匹配1个或多个的表达式

image
运行结果:

image
分析:匹配字符a并且c一次或者多次,所以会匹配ac或者accccc
? : 匹配0次或1次,非贪婪方式

image
运行结果:
分析:表达式“ac?” 匹配字符a或者ac(?只匹配0次或者1次,比较懒惰,不像上面的+或者*会匹配多次)
.? : 这三个特殊符号上面都讲过了,.是匹配任意字符匹配0次或者多次,连在一起使用也就是匹配全文了,加上?号,非贪婪模式匹配,将尽可能少的匹配结果。

image
匹配结果:

image
4小结正则匹配的语法是通用的,大家学会这些特殊字符,无论什么语言都能迅速入门。所以有必要好好学习一下。
柠檬为大家准备了一些python的学习教程分享,希望可以帮助到大家。

