设为首页 加入收藏

TOP

Python正则表达式基础(三)
2017-09-30 13:01:35 】 浏览:9114
Tags:Python 正则 表达式 基础

  • 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']

  • 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
  • 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!
    

      


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

     


  • 首页 上一页 1 2 3 下一页 尾页 3/3/3
    】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
    上一篇python for循环巧妙运用(迭代、.. 下一篇python之list

    最新文章

    热门文章

    Hot 文章

    Python

    C 语言

    C++基础

    大数据基础

    linux编程基础

    C/C++面试题目