Python爬虫实践(七):正则表达式(2) re模块的使用

来源:互联网 发布:数据库服务器 编辑:程序博客网 时间:2024/05/16 09:30

前面说到re模块,可用于正则表达式,匹配字符主要用到的函数有以下几种:

#以下为匹配所用函数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])

方法/属性——-作用
- match() 决定 RE 是否在字符串刚开始的位置匹配
- search() 扫描字符串,找到这个 RE 匹配的位置
- re.split() 按照能够匹配的子串将string分割后返回列表

import repattern = re.compile(r'\d+')print re.split(pattern,'one1two2three3four4')## 输出 # ['one', 'two', 'three', 'four', '']

-findall() 找到 RE 匹配的所有子串,并把它们作为一个列表返回

import repattern = re.compile(r'\d+')print re.findall(pattern,'one1two2three3four4')### 输出 #### ['1', '2', '3', '4']

-finditer() 找到 RE 匹配的所有子串,并把它们作为一个迭代器返回

import repattern = re.compile(r'\d+')for m in re.finditer(pattern,'one1two2three3four4'):    print m.group(),### 输出 #### 1 2 3 4

-re.sub(pattern, repl, string[, count]) 使用repl替换string中每一个匹配的子串后返回替换后的字符串。

import repattern = re.compile(r'(\w+) (\w+)')s = 'i say, hello world!'print re.sub(pattern,r'\2 \1', s)def func(m):    return m.group(1).title() + ' ' + m.group(2).title()print re.sub(pattern,func, s)### output #### say i, world hello!# I Say, Hello World!
  • repl是一个字符串时,可以使用\id\g\g引用分组,但不能使用编号0。
  • repl是一个方法时,这个方法应当只接受一个参数(Match对象),并返回一个字符串用于替换(返回的字符串中不能再引用分组)。
  • count用于指定最多替换次数,不指定时全部替换。

-re.subn() 返回 (sub(repl, string[, count]) 的替换次数)。

import repattern = re.compile(r'(\w+) (\w+)')s = 'i say, hello world!'print re.subn(pattern,r'\2 \1', s)def func(m):    return m.group(1).title() + ' ' + m.group(2).title()print re.subn(pattern,func, s)### output #### ('say i, world hello!', 2)# ('I Say, Hello World!', 2)

pattern说明

以上这些函数中所用到的
pattern = re.compile(string[,flag])

而以上的flags 参数是字符的匹配模式,如果要同时应用多个匹配模式(规则),则可以使用按位或运算符 | .
flags可选值:
- re.I (IGNORECASE): 忽略大小写(括号内是完整写法,下同)
- re.M (MULTILINE): 多行模式,改变’^’和’$’的行为(参见上图)
- re.S (DOTALL): 点任意匹配模式,改变’.’的行为
- re.L (LOCALE): 使预定字符类 \w \W \b \B \s \S 取决于当前区域设定
- re.U (UNICODE): 使预定字符类 \w \W \b \B \s \S \d \D 取决于unicode定义的字符属性
- re.X (VERBOSE): 详细模式。这个模式下正则表达式可以是多行,忽略空白字符,并可以加入注释。

注:如果在pattern生成时已经指明了flags,那么在匹配函数方法中就不需要传入这个参数了



最后,通过一例子来理解:

# -*- coding: utf-8 -*-# 导入re模块import re# 将正则表达式编译成Pattern对象,注意hello前面的r的意思是“原生字符串”pattern = re.compile(r'hello')# 使用re.match匹配文本,获得匹配结果,无法匹配时将返回Nonestrings=['hello','Hello','HELLOGIRL','hellooo','heyloo']i=1for str in strings:    result=re.match(pattern,str)    if result:        print result.group()        i+=1    else:        print "第 %d 个匹配失败"%(i)        i+=1

运行结果:

hello第 2 个匹配失败第 3 个匹配失败hello第 5 个匹配失败

加入re.X

如果将上面的pattern改为
pattern = re.compile(r'hello*',re.I)
由上面的知识可知,re.I 即忽略大小写的意思,则运行结果:

helloHelloHELLOhello第 5 个匹配失败

如果pattern改为:
pattern = re.compile('hey*')
结果:

he第 2 个匹配失败第 3 个匹配失败hehey
0 0
原创粉丝点击