Python基础 - 正则表达式
什么是正则表达式
在编写处理字符串的程序或网页时,经常会有查找符合某些复杂规则的字符串的需要。正则表达式就是描述这写规则的工具。
常用元字符:
- [] :表示字符集,在字符集中的任意一个自否即可满足条件
- {} :表示量词,刚好出现的次数,{n,m}表示最少n次,最多m次;
- \d :表示0~9的数字;
- \D :表示除数字以外的字符
- \w :表示大小写的英文字母、数字、下划线
- \W :表示除大小写的英文字母、数字、下划线以外的字符
- \s :表示空白字符,包括 \t \n tab
- \S :表示不是空白字符
- | :分支
- ? :匹配0次或1次
- *:匹配0次或多次
- *? :惰性匹配,匹配0次或1次,尽量少的匹配。
常用函数:
- match(pattern, string,flags=0) :用正则表达式规则匹配字符串,成功则返回匹配对象,否则返回NONE
- fullmatch(pattern, string,flags=0) :match函数的完全匹配
- search(pattern, string,flags=0) :搜索字符串中第一次出现匹配正则表达式规则的对象,成功则返回匹配对象,否则返回NONE
- findall(pattern, string,flags=0) :查找字符串中所有满足正则表达式规则的对象,返回一个列表
- finiter(pattern, string,flags=0) :查找字符串中所有满足正则表达式规则的对象,返回一个迭代器
- sub(pattern, repl, string, count=0, flags=0) :用指定的字符串替换满足正则表达式的对象,可以用count控制替换次数
- split(pattern, string, maxsplit=0, flags=0) :用正则表达式的模式分隔符拆分字符串,返回一个列表。
import re
# 通过正则表达式判断输入是否是有效手机号码
tel = input('请输入手机号码:')
# fullmatch 实现完全匹配
matcher = re.fullmatch(r'1[3-9][0-9]{9}', tel)
# match也能实现完全匹配
# ^ 和 $ 表示字符串的开始和结束,限制字符串长度
matcher2 = re.match(r'^1[3-9][0-9]{9}$', tel)
# 如果字符串跟正则表达式匹配成功,则返回一个匹配对象,否则返回空值
print(matcher, matcher2)
# 在字符串中获取想要的字符或字符串
content = """余婷的手机号不是13564889515,不是15632158948,,也不是120
骆昊135的手机号是13554892193,骆昊的存款没有15486513215161元。
"""
# 前瞻语法(向后看)---> (?=\d) 后面是数字,(?!\d) 后面不能是数字
# 回顾语法(向前看)---> (?<=\d) 前面是数字,(?!\d) 前面不能是数字
# 方法1:
matcher3 = re.search(r'(?<!\d)1[3-9][0-9]{9}(?!\d)', content)
while matcher3:
print(matcher3.group())
content = content[matcher3.end():]
matcher3 = re.search(r'(?<!\d)1[3-9][0-9]{9}(?!\d)', content)
方法2:
items = re.findall(r'(?<!\d)1[3-9][0-9]{9}(?!\d)', content)
for item in items:
print(item)
方法3:
items_obj = re.finditer(r'(?<!\d)1[3-9][0-9]{9}(?!\d)', content)
for item in items_obj:
print(item)
抓取搜狐新闻页新闻链接和标题
import re
import requests
from future.backports.urllib.parse import urljoin
resp = requests.get('https://sohu.com/index.html')
if resp.status_code == 200:
anchors_list = re.findall(r'<a.*?href="(.*?)".*?title="(.*?)".*?>', resp.text)
for href, title in anchors_list:
if not href.startswith('https://'):
href = urljoin('https://sohu.com', href)
print(href)
print(title)