- re模块
- 1、基本结构
- 2、常用函数
- 2.1、match函数
- 2.2、search函数
- 2.3、findall函数
- 2.4、sub函数
- 2.5、group函数与groups函数
- 3、一些要注意的
写在前面:以前有想要学爬虫,没有坚持学习下来,现在用re模比较多,于是系统学一下,顺便记录下来,提高使用re模块的效率 re模块 1、基本结构
import re
pattern = r''
#原生字符串模式
#也可以用下面的定义模式
pattern = re.compile('正则表达式')
string = ''
re.match(pattern, string, flag)
2、常用函数
2.1、match函数
re.match(pattern, string, flag) 用法:在字符串开头匹配,匹配到就结束 匹配成功返回一个对象,要想返回具体字符串,用group() 失败发挥一个none2.2、search函数
与match基本相同,不过是在任意位置匹配
2.3、findall函数re.findall(pattern, string, flag) 找到匹配分组里所有字符串,返回的是一个列表2.4、sub函数
re.sub(pattern, target, string, flag) pattern 要被替换的字符串 target 要替换成的字符串2.5、group函数与groups函数
- m.group(N) 返回第几组括号匹配的字符串
- m.group() == m.group(0) 返回所有匹配的字符,与括号无关
- m.groups() 返回所有括号匹配的字符,返回的类型是一个元组 m.groups() = (m.group(0), m.group(1), ……)
- 用search、match匹配返回的是一个对象,要用group分组,显示出来
- r 原生字符串和re.complile是等价的
- findall遇到括号嵌套的问题,原则是从左到右,从外到内



