您现在所的位置:创意网 - 创艺资讯 - 娱乐八卦

[Python]网络爬虫(七):Python中的正则表达式教程(4)

标签:娱乐八卦日期:2016-04-02 05:11小编:二锅头热度:

match()只有在0位置匹配成功的话才有返回,如果不是开始位置匹配成功的话,match()就返回none
例如:
print(re.match(‘super’, ‘superstition’).span())

会返回(0, 5)

print(re.match(‘super’, ‘insuperable’))

则返回None

search()会扫描整个字符串并返回第一个成功的匹配
例如:

print(re.search(‘super’, ‘superstition’).span())

返回(0, 5)
print(re.search(‘super’, ‘insuperable’).span())

返回(2, 7)

看一个search的实例:

# -*- coding: utf-8 -*- #一个简单的search实例 import re # 将正则表达式编译成Pattern对象 pattern = re.compile(r'world') # 使用search()查找匹配的子串,不存在能匹配的子串时将返回None # 这个例子中使用match()无法成功匹配 match = pattern.search('hello world!') if match: # 使用Match获得分组信息 print match.group() ### 输出 ### # world



3.split

split(string[, maxsplit]) | re.split(pattern, string[, maxsplit]):
按照能够匹配的子串将string分割后返回列表。

maxsplit用于指定最大分割次数,不指定将全部分割。

import re p = re.compile(r'\d+') print p.split('one1two2three3four4') ### output ### # ['one', 'two', 'three', 'four', '']


4.findall

findall(string[, pos[, endpos]]) | re.findall(pattern, string[, flags]):
搜索string,以列表形式返回全部能匹配的子串。

import re p = re.compile(r'\d+') print p.findall('one1two2three3four4') ### output ### # ['1', '2', '3', '4']


5.finditer

finditer(string[, pos[, endpos]]) | re.finditer(pattern, string[, flags]):
搜索string,返回一个顺序访问每一个匹配结果(Match对象)的迭代器。

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

6.sub

sub(repl, string[, count]) | re.sub(pattern, repl, string[, count]):
使用repl替换string中每一个匹配的子串后返回替换后的字符串。
当repl是一个字符串时,可以使用\id或\g<id>、\g<name>引用分组,但不能使用编号0。
当repl是一个方法时,这个方法应当只接受一个参数(Match对象),并返回一个字符串用于替换(返回的字符串中不能再引用分组)。
count用于指定最多替换次数,不指定时全部替换。

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

subn(repl, string[, count]) |re.sub(pattern, repl, string[, count]):
返回 (sub(repl, string[, count]), 替换次数)。

import re p = re.compile(r'(\w+) (\w+)') s = 'i say, hello world!' print p.subn(r'\2 \1', s) def func(m): return m.group(1).title() + ' ' + m.group(2).title() print p.subn(func, s) ### output ### # ('say i, world hello!', 2) # ('I Say, Hello World!', 2)
至此,Python的正则表达式基本介绍就算是完成了^_^

顶一下
(0)
0%
踩一下
(0)
0%