re模块的方法

match方法
match(string[, pos[, endpos]])
string:匹配使用的文本,
pos: 文本中正则表达式开始搜索的索引。及开始搜索string的下标
endpos: 文本中正则表达式结束搜索的索引。
如果不指定pos,默认是从开头开始匹配,如果匹配不到,直接返回None
 
import re
pattern = re.compile(r'\w*(hello w.*)(hello l.*)')
result = pattern.match(r'aahello world hello ling')
print(result)
result2 = pattern.match(r'hello world hello ling')
print(result2.groups())
结果:
None
('hello world ', 'hello ling')
解释:如果不指定pos的话,默认是从字符串开始位置匹配,匹配不到就返回None,以上所有的pattern都是一个match对象,他在查找结果的时候有自己的方法,我们在后一节会详细接受他的方法。
 
search方法
search(string[, pos[, endpos]])
这个方法用于查找字符串中可以匹配成功的子串。从string的pos下标处起尝试匹配pattern,如果pattern结束时仍可匹配,则返回一个Match对象;若无法匹配,则将pos加1后重新尝试匹配;直到pos=endpos时仍无法匹配则返回None。下面看个列子:
 
import re
pattern = re.compile(r'(hello w.*)(hello l.*)')
result1 = pattern.search(r'aahello world hello ling')
print(result1.groups())
结果:
('hello world ', 'hello ling')
 
 
split方法
split(string[, maxsplit])
按照能够匹配的子串将string分割后返回列表。maxsplit用于指定最大分割次数,不指定将全部分割。
import re
p = re.compile(r'\d+')
print(p.split('one1two2three3four4'))
结果:
['one', 'two', 'three', 'four', '']
解释:直接把p的正则当成是分隔符,然后把最后的字符串用p进行分割,然后返回回去
 
findall方法
findall(string[, pos[, endpos]])
搜索string,以列表形式返回全部能匹配的子串.
import re
p = re.compile(r'\d+')
print(findall('one1two2three3four4'))
结果:
['1', '2', '3', '4']
结果:findall是把匹配到的字符串最后一列表的形式返回回去
 
finditer方法
finditer(string[, pos[, endpos]])
搜索string,返回一个顺序访问每一个匹配结果(Match对象)的迭代器。
import re
p = re.compile(r'\d+')
print(type(p.finditer('one1two2three3four4')))
for m in p.finditer('one1two2three3four4'):
    print(type(m))
print(m.group())
结果:<type 'callable-iterator'>
<type '_sre.SRE_Match'>
1
<type '_sre.SRE_Match'>
2
<type '_sre.SRE_Match'>
3
<type '_sre.SRE_Match'>
4
解释:
p.finditer('one1two2three3four4')是一个迭代器,而返回的每个m都是match对象,group方法也会在下一节进行详细介绍。
 
sub方法
sub(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))
结果:
say i, world hello!
I Say, Hello World!
解释:
\(id)就是匹配的括号的内容,id从默认从1开始计数
m.group(1)是一个字符串,调用字符串的title()方法,所有单词的搜字母大写。
 
 

<wiz_tmp_tag id="wiz-table-range-border" contenteditable="false" style="display: none;">

posted on 2017-11-16 00:09  song-liang  阅读(934)  评论(0编辑  收藏  举报

导航