正则表达式

来源:互联网 发布:淘宝可以举报卖家吗 编辑:程序博客网 时间:2024/05/22 07:06

re模块

  • re.compile
import sysreload(sys)sys.setdefaultencoding('utf-8')import re  b = re.compile(r"\d+\.\d*")  match21 = b.match('3.1415')  match22 = b.match('33')   if match21:      # 使用Match获得分组信息      print match21.group()  else:      print u'match21不是小数'  if match22:      # 使用Match获得分组信息      print match22.group()  else:      print u'match22不是小数'  #若开头不将编码方式设为utf-8,此处变为unicode会报错
  • re.match
import re  # 匹配如下内容:单词+空格+单词+任意字符  m = re.match(r'(\w+) (\w+)(?P<sign>.*)', 'hello world!')  print "m.string:", m.string  #匹配上使用的文本:hello worldprint "m.re:", m.re          print "m.pos:", m.pos       #文本中正则表达式开始搜索的索引:0print "m.endpos:", m.endpos  #正则表达式结束的索引:12print "m.lastindex:", m.lastindex  #最后一个被捕获的分组在文中的索引:3print "m.lastgroup:", m.lastgroup  #最后一个被捕获的分组的别名:signprint "m.group():", m.group()  #不填写参数相当于group(0),返回整个匹配的子串print "m.group(1,2):", m.group(1, 2)  #('hello', 'world')print "m.groups():", m.groups()       #以元组形式返回全部分组截获的字符串('hello', 'world', '!')print "m.groupdict():", m.groupdict() #返回以有别名的组的别名为键,以该组截获的子串为值的字典:{'sign': '!'}print "m.start(2):", m.start(2)       #返回指定的组截获的子串在string中的起始索引(子串第一个字符的索引):6print "m.end(2):", m.end(2)        #返回指定的组截获的子串在string中的结束索引(子串最后一个字符的索引+1):11print "m.span(2):", m.span(2)     #返回(start(group), end(group)):(6,11)print r"m.expand(r'\g<2> \g<1>\g<3>'):", m.expand(r'\2 \1\3')  #world hello!
  • pattern
    • match:pos和endpos的默认值分别为0和len(string)
    • search:扫描整个string查找匹配
    • split:按照能够匹配的子串将string分割后返回列表
    • findall:以列表形式返回全部能匹配的子串
    • sub:匹配并替换
    • subn
#match&search演示import re  # 将正则表达式编译成Pattern对象  pattern = re.compile(r'world')  # 使用search()查找匹配的子串,不存在能匹配的子串时将返回None  # 这个例子中使用match()无法成功匹配  match = pattern.search('hello world!')  if match:      # 使用Match获得分组信息      print match.group()      print match.span()#结果如下:world(6, 11)
import re  p = re.compile(r'\d+')  print p.split('one1two2three3four4')  print p.findall('one1two2three3four4') print p.search('one1two2three3four4').group() 结果如下:['one', 'two', 'three', 'four', '']['1', '2', '3', '4']1 
#sub用法import re  #p表示单词字符、空格、单词字符   p = re.compile(r'(\w+) (\w+)')  s = 'i say, hello world! barney'  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! barneyI Say, Hello World! barney

参考资料:
http://blog.csdn.net/pleasecallmewhy/article/details/8929576
http://www.cnblogs.com/afarmer/archive/2011/08/29/2158860.html

0 0