您的位置:首页 > 编程语言 > Python开发

Python爬虫实践(八):正则表达式re模块(2)

2016-06-21 14:44 841 查看
前面的例子我们打印出了
result.group()
,其实每个匹配方法还有其他的属性/方法

re.match(pattern, string[, flags])
re.search(pattern, string[, flags])
re.split(pattern, string[, maxsplit])
re.findall(pattern, string[, flags])
re.finditer(pattern, string[, flags])
re.sub(pattern, repl, string[, count])
re.subn(pattern, repl, string[, count])


属性

string
: 匹配时使用的文本。

re
: 匹配时使用的Pattern对象。

pos
: 文本中正则表达式开始搜索的索引。值与
Pattern.match()
Pattern.seach()
方法的同名参数相同。

endpos
: 文本中正则表达式结束搜索的索引。值与Pattern.match()和Pattern.seach()方法的同名参数相同。

lastindex
: 最后一个被捕获的分组在文本中的索引。如果没有被捕获的分组,将为None。

lastgroup
: 最后一个被捕获的分组的别名。如果这个分组没有别名或者没有被捕获的分组,将为None。

方法:

group([group1, …])
:

获得一个或多个分组截获的字符串;指定多个参数时将以元组形式返回。group1可以使用编号也可以使用别名;编号0代表整个匹配的子串;不填写参数时,返回group(0);没有截获字符串的组返回None;截获了多次的组返回最后一次截获的子串。

groups([default])
:

元组形式返回全部分组截获的字符串。相当于调用
group(1,2,…last)
default
表示没有截获字符串的组以这个值替代,默认为
None


groupdict([default])
:

返回以有别名的组的别名为键、以该组截获的子串为值的字典,没有别名的组不包含在内。
default
含义同上。

start([group])
:

返回指定的组截获的子串在
string
中的起始索引(子串第一个字符的索引)。
group
默认值为
0


end([group])
:

返回指定的组截获的子串在
string
中的结束索引(子串最后一个字符的索引+1)。
group
默认值为0。

span([group])
:

返回
(start(group), end(group))


expand(template)
:

将匹配到的分组代入
template
中然后返回。

template
中可以使用
\id
\g
\g
引用分组,但不能使用编号
0


\10
将被认为是第10个分组,如果你想表达
\1
之后是字符’0’,只能使用
\g0


在上面我们介绍了7个工具方法,例如match,search等等,不过调用方式都是
re.match
re.search
的方式,其实还有另外一种调用方式,可以通过
pattern.match
pattern.search
调用,这样调用便不用将pattern作为第一个参数传入了,大家想怎样调用皆可。

match(string[, pos[, endpos]]) | re.match(pattern, string[, flags])
search(string[, pos[, endpos]]) | re.search(pattern, string[, flags])
split(string[, maxsplit]) | re.split(pattern, string[, maxsplit])
findall(string[, pos[, endpos]]) | re.findall(pattern, string[, flags])
finditer(string[, pos[, endpos]]) | re.finditer(pattern, string[, flags])
sub(repl, string[, count]) | re.sub(pattern, repl, string[, count])
subn(repl, string[, count]) |re.sub(pattern, repl, string[, count])
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 爬虫