本章总体难度不大
15.1节需要理解‘搜索(search)’和‘匹配(match)’,匹配是指一个字符串从头开始部分或全部地与正则表达式匹配,而搜索是指字符串部分或全部与正则表达式匹配。两者不同之处在于匹配必须是“从字符串开头起始”,而搜索既可以从字符串开头起始,也可以从字符串中间起始。
15.2节讲正则表达式使用的特殊符号和字符,基本没什么难度,注意在使用闭包操作符(*, +, ?, {})时,默认是贪心模式,以{M, N} 为例,贪心模式是指在字符串匹配次数尽可能地向N靠拢,而如果在后面加?,即{M, N}?,就是非贪心模式,匹配次数尽量向M靠拢。其余操作符也是类似的,在15.4节有例子提及。
15.3节,re模块。
compile(pattern, flag=0),对正则表达式pattern进行编译,返回regex对象,这个不理解。
match()和search()如果匹配成功,返回匹配对象,否则返回None。
group()主要是返回特定子组,只是奇怪为什么编号是从1开始的。groups()以元组形式返回所有子组。
findall()、sub()、subn()和split()都比较简单。
书中第一个例子:
#-*-coding: utf-8-*-
from os import popen
from re import split
f = popen('dir', 'r') # os.popen()是python脚本调用另一个程序的方法
for eachLine in f:
print split('\s+', eachLine.strip())
f.close()
15.4节,例子
#-*-coding: utf-8-*-
from random import randint, choice
from string import lowercase
from sys import maxint
from time import ctime
doms = ('com', 'edu', 'net', 'org', 'gov')
for i in range(randint(5, 10)):
dtint = randint(0, maxint-1) # 选择一个日期,以时间戳形式表示
dtstr = ctime(dtint) # 将时间戳转化成时间字符串
shorter = randint(4, 7) # 邮箱用户名长度
em = ''
for j in range(shorter):
em += choice(lowercase) # 产生邮箱用户名
longer = randint(shorter, 12) # 邮箱服务器名长度
dn = ''
for j in range(longer):
dn += choice(lowercase) # 产生邮箱服务器名
print '%s::%s@%s.%s::%d-%d-%d' % (dtstr, em, dn, choice(doms), dtint, shorter, longer) # 时间::邮箱::时间戳-邮箱用户名长度-邮箱服务器名长度
注意15.4.2中的“贪心匹配部分”。