1 正则表达式的符号和特殊字符
2 正则表达式的匹配和分组
3 re库:compile match search findall sub split group groups groupdict
1. 正则表达式



有三个匹配模式:
- 简单匹配
- 多个匹配
- 匹配任意字符
2. 正则表达式的使用
a*bc 匹配0次或者多次a
a+bc 匹配1次或者多次a
a?bc 匹配0次或者1次a
a{3}bc 匹配3次a
a{2,5}bc 匹配2-5次a,优先匹配最多次的
3. 正则表达式匹配同类型及边界匹配
匹配同类型:
- \d 数字
- \w 数字和字符
- \s 空格
边界匹配: - ^ 开头
- $ 结尾
4. 正则表达式匹配选项
使用\来进行转义特殊字符
匹配选项:
- [a-zA-Z]{3} 指定匹配3个
- [^abc]{2} 指定不匹配这两个
5. 正则表达式分组
重复一个字符串进行匹配时
- () 匹配 如 (\d{1,3}.){3}\d{1,3}
-
组号:
- \1 \2 反向引用 如 He (l..e)s her \1r. 来匹配 He loves her lover. He likes her liker.
6. 贪婪和非贪婪模式
- 贪婪模式,默认是贪婪模式,尽可能多的去匹配 如 a.+b
- 非贪婪模式,尽可能少的去匹配 a.+?b
7. 实战匹配
- 身份证匹配: (\d{6})(\d{4})((\d{2})(\d{2}))\d{1}([0-9]|X)
- 邮箱正则匹配:[a-zA-Z0-9_-]+@[a-zA-Z0-9-]+(.[a-zA-Z0-9-]+)*(.[a-zA-Z]{2,5})
8. python re模块

- compile() 和 match()
import re
pattern = re.compile(r'Hello', re.I)
rest = pattern.match('hello word')
print(dir(rest))
print(rest.string)
- findall() 和 search()
findall()是找到所有匹配的内容,返回一个list;search()是找到第一个匹配的内容,返回一个对象
# 有两种方式,一个是编译,一个是不编译
# 编译
p = re.compile(r'[a-z]+', re.I)
rest = p.findall(content)
# 不编译
all_rest = re.findall(r'[a-z]+', content, re.I)
- match() 和 search()
match是从开头开始匹配,如果匹配不是就返回空;search是只要找到就ok - group(), groups(), groupdict()
group(1) 返回该位置的
groups() 返回tuple
groupdict() 返回命名的group
p = re.compile(r'(\d{6})(?P<year>\d{4})((?P<month>\d{2})(\d{2}))\d{1}([0-9]|X)')
id1 = '232321199410270017'
rest1 = p.search(id1)
print(rest1.group(4))
print(rest1.groups())
print(rest1.groupdict())
- split() 和 sub()
split(pattern, string, max=0) 分割匹配的字符(分隔符为匹配的字符)
sub(pattern, replace, string, max) 替换匹配的字符
s = 'one1two2three'
p = re.compile(r'\d+')
rest = p.split(s, 2)
print(rest)
# 替换
s = 'one1two2three'
p = re.compile(r'\d+')
rest = p.sub('@', s)
# 替换位置
s1 = 'hello world'
p1 = re.compile(r'(\w+) (\w+)')
rest1 = p1.sub('r\2 \1', s1)
# 使用函数或者lambda来匹配
def f(m):
return m.group(2).upper() + ' ' + m.group(1)
rest2 = p1.sub(f, s1)
rest3 = p1.sub(lambda m: m.group(2).upper() + ' ' + m.group(1), s1)
9. 实战取图片地址
import re
def test_image_url_extraction():
with open('sample.html', encoding='utf-8') as f:
html = f.read()
p = re.compile(r'<img.+?src=\"(?P<src>.+?)\".+?>', re.M|re.I)
list_img = p.findall(html)
for i in list_img:
print(i.replace('&', '&'))
# requests库去爬虫
网友评论