python数据清洗:正则表达式re(配合爬虫)
Python的re模块(正则表达式)提供各种正则表达式的匹配操作。在绝大多数情况下能够有效地实现对复杂字符串的分析并取出相关信息。
- 在线验证
访问这个网址: https://regex101.com/
选中使用语言后输入 搜索文本 和 表达式,查看你的表达式是否能正确匹配到字符串。 - 基本语法(匹配规则)。
- pattern对象
pattern对象是由我们传入字符串对象,通过compile方法生成。利用这个对象来进行下一步的匹配。
re.compile(string[,flag])
-
匹配所用函数:re.match(pattern, string[, flags])
match函数将会从String(待匹配的字符串)的开头开始,尝试匹配pattern,一直向后匹配。如果中途匹配pattern成功,则终止匹配,返回匹配结果。如果无法匹配或者到字符串末尾还未匹配到,则返回None。 -
匹配所用函数:re.search(pattern, string[, flags])
Search函数会扫描整个string字符串查找匹配,存在的话返回匹配结果,不存在则返回None。 -
匹配所用函数:re.split(pattern, string[, maxsplit])
split函数可以按照pattern匹配模式将string字符串分割后返回列表,其中maxsplit参数可以指定最大分割次数,不指定则将字符串全部分割。 -
匹配所用函数:re.findall(pattern, string[, flags])
findall函数作用是搜索整个字符串,以列表形式返回全部能匹配的子串。 -
匹配所用函数:re.finditer(pattern, string[, flags])
finditer函数作用是搜索整个字符串,返回一个符合匹配结果(Match对象)的迭代器。 -
匹配所用函数:re.sub(pattern, repl, string[, count])
sub函数对匹配的文本进行替换 -
匹配所用函数:re.subn(pattern, repl, string[, count])
subn可以指定替换次数,不指定则默认替换全部。
https://mp.weixin.qq.com/s/8-kdoVnW9QzFx0iq_LiZMg
http://www.byhy.net/tut/py/extra/regex/