python-re模块

python re模块中的用法:

1,compile: re.compile(strPattern[, flag])

pattern=re.compile(r"<div.*?>(.*?)</div>")

得到的是一个pattern对象,属性有:

  1. pattern: 编译时用的表达式字符串。
  2. flags: 编译时用的匹配模式。数字形式。
  3. groups: 表达式中分组的数量。
  4. groupindex: 以表达式中有别名的组的别名为键、以该组对应的编号为值的字典,没有别名的组不包含在内。 
 1 #! /usr/bin/env python
 2 #coding=utf-8
 3 import re
 4 pattern=re.compile(r'(\w+) (\w+)(?P<sign>.*)',re.I|re.M)
 5 print pattern.pattern
 6 print pattern.flags
 7 print pattern.groups
 8 print pattern.groupindex
 9 "(\w+) (\w+)(?P<sign>.*)
10 10
11 3
12 {'sign': 3}"

2,match:match(string[, pos[, endpos]]) | re.match(pattern, string[, flags]):

如:matchObj = re.match( r'(.*) are (.*?) .*', string, re.M|re.I)

       或

       pattern=re.compile("hello",re.S)

       matchObj=pattern.match("hello world!")

这个方法将从string的pos下标处起尝试匹配pattern;

如果pattern结束时仍可匹配,则返回一个Match对象;

如果匹配过程中pattern无法匹配,或者匹配未结束就已到达endpos,则返回None。

pos和endpos的默认值分别为0和len(string);

re.match()无法指定这两个参数,参数flags用于编译pattern时指定匹配模式。

注意:这个方法并不是完全匹配。

当pattern结束时若string还有剩余字符,仍然视为成功。

想要完全匹配,可以在表达式末尾加上边界匹配符'$'。

得到的是Match对象,属性有:

  1. string: 匹配时使用的文本。
  2. re: 匹配时使用的Pattern对象。
  3. pos: 文本中正则表达式开始搜索的索引。值与Pattern.match()和Pattern.seach()方法的同名参数相同。
  4. endpos: 文本中正则表达式结束搜索的索引。值与Pattern.match()和Pattern.seach()方法的同名参数相同。
  5. lastindex: 最后一个被捕获的分组在文本中的索引。如果没有被捕获的分组,将为None。
  6. lastgroup: 最后一个被捕获的分组的别名。如果这个分组没有别名或者没有被捕获的分组,将为None。

方法:

    1. group([group1, …]):
      获得一个或多个分组截获的字符串;指定多个参数时将以元组形式返回。group1可以使用编号也可以使用别名;编号0代表整个匹配的子串;不填写参数时,返回group(0);没有截获字符串的组返回None;截获了多次的组返回最后一次截获的子串。
    2. groups([default]):
      以元组形式返回全部分组截获的字符串。相当于调用group(1,2,…last)。default表示没有截获字符串的组以这个值替代,默认为None。
    3. groupdict([default]):
      返回以有别名的组的别名为键、以该组截获的子串为值的字典,没有别名的组不包含在内。default含义同上。
    4. start([group]):
      返回指定的组截获的子串在string中的起始索引(子串第一个字符的索引)。group默认值为0。
    5. end([group]):
      返回指定的组截获的子串在string中的结束索引(子串最后一个字符的索引+1)。group默认值为0。
    6. span([group]):
      返回(start(group), end(group))。
    7. expand(template):
      将匹配到的分组代入template中然后返回。template中可以使用\id或\g<id>、\g<name>引用分组,但不能使用编号0。\id与\g<id>是等价的;但\10将被认为是第10个分组,如果你想表达\1之后是字符'0',只能使用\g<1>0。
 1 #! /usr/bin/env python
 2 #coding=utf-8
 3 import re
 4 pattern=re.compile(r'<p.*?>#(\d*)(\w+) (\w+)(?P<sign>.*)#.*?',re.I|re.M)
 5 str="<p style='font-family:arial;color:red;font-size:20px;'>#6748hello word!#6748</p>"
 6 Match=pattern.match(str)
 7 print "Match.string:", Match.string
 8 print "Match.re:", Match.re
 9 print "Match.pos:", Match.pos
10 print "Match.endpos:",  Match.endpos
11 print "Match.lastindex:", Match.lastindex
12 print "Match.lastgroup:", Match.lastgroup
13 
14 print "Match.group():", Match.group()  
15 print "Match.group(1,2):", Match.group(1, 2)  
16 print "Match.groups():", Match.groups()  
17 print "Match.groupdict():", Match.groupdict()  
18 print "Match.start(2):", Match.start(2)  
19 print "Match.end(2):", Match.end(2)  
20 print "Match.span(2):", Match.span(2)  
21 print r"Match.expand(r'\g<2> \g<3> \g<4> \g<1>'):", Match.expand(r'\2 \3 \4 \1') 
22 
23 '''
24 atch.string: <p style='font-family:arial;color:red;font-size:20px;'>#6748hello word!#6748</p>
25 Match.re: <_sre.SRE_Pattern object at 0x0263D600>
26 Match.pos: 0
27 Match.endpos: 80
28 Match.lastindex: 4
29 Match.lastgroup: sign
30 Match.group(): <p style='font-family:arial;color:red;font-size:20px;'>#6748hello word!#
31 Match.group(1,2): ('6748', 'hello')
32 Match.groups(): ('6748', 'hello', 'word', '!')
33 Match.groupdict(): {'sign': '!'}
34 Match.start(2): 60
35 Match.end(2): 65
36 Match.span(2): (60, 65)
37 Match.expand(r'\g<2> \g<3> \g<4> \g<1>'): hello word ! 6748
38 
39 '''

 

3,search
search(string[, pos[, endpos]]) | re.search(pattern, string[, flags]):
这个方法用于查找字符串中可以匹配成功的子串。

从string的pos下标处起尝试匹配pattern,

如果pattern结束时仍可匹配,则返回一个Match对象;

若无法匹配,则将pos加1后重新尝试匹配;

直到pos=endpos时仍无法匹配则返回None。

pos和endpos的默认值分别为0和len(string));

re.search()无法指定这两个参数,参数flags用于编译pattern时指定匹配模式。

那么它和match有什么区别呢?

match()函数只检测re是不是在string的开始位置匹配,

search()会扫描整个string查找匹配,

 

,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)

 

 4,split

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

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

  

  1. import re  
  2.    
  3. p = re.compile(r'\d+')  
  4. print p.split('one1two2three3four4')  
  5.    
  6. ### output ###   
  7. # ['one', 'two', 'three', 'four', '']  

 

5.findall

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

 [python] view plaincopyprint?在CODE上查看代码片派生到我的代码片

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

 

6,finditer

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

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

 7,sub

 

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

  1. import re  
  2.    
  3. p = re.compile(r'(\w+) (\w+)')  
  4. s = 'i say, hello world!'  
  5.    
  6. print p.sub(r'\2 \1', s)  
  7.    
  8. def func(m):  
  9.     return m.group(1).title() + ' ' + m.group(2).title()  
  10.    
  11. print p.sub(func, s)  
  12.    
  13. ### output ###   
  14. # say i, world hello!   
  15. # I Say, Hello World!   

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

    1. import re  
    2.    
    3. p = re.compile(r'(\w+) (\w+)')  
    4. s = 'i say, hello world!'  
    5.    
    6. print p.subn(r'\2 \1', s)  
    7.    
    8. def func(m):  
    9.     return m.group(1).title() + ' ' + m.group(2).title()  
    10.    
    11. print p.subn(func, s)  
    12.    
    13. ### output ###   
    14. # ('say i, world hello!', 2)   
    15. # ('I Say, Hello World!', 2)  

 

 转自: http://blog.csdn.net/pleasecallmewhy/article/details/8929576

posted @ 2014-08-24 15:32  fkissx  阅读(3328)  评论(0编辑  收藏  举报