• Python3 正则表达式


    re.match

    尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match()就返回none.

    re.match(pattern, string, flags=0)

    pattern : 正则表达式

    string : 要匹配的字符串

    flags : 标志位

    匹配成功返回一个匹配的对象,否则返回None.

    用group(num) 或 groups() 匹配对象函数来获取匹配表达式

    #!/usr/bin/python3
    import re
    
    line = "Cats are smarter than dogs"
    
    matchobj = re.match(r'(.*) are (.*?) .*', line, re.M|re.I)
    
    if matchobj:
        print("matchobj.group() : ", matchobj.group())
        print("matchobj.group(1) : ", matchobj.group(1))
        print("matchobj.group(2) : ", matchobj.group(2),"
    ")
    
        print("matchobj.groups() : ", matchobj.groups())
        print("matchobj.groups()[0] : ", matchobj.groups()[0])
        print("matchobj.groups()[1] : ", matchobj.groups()[1])
    else:
        print("error")
    

    re.search

    扫描整个字符串并返回第一个成功的匹配。

    re.search(pattern, string, flags=0)

    区别

    re.match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None;而re.search匹配整个字符串,直到找到一个匹配。

    #!/usr/bin/python3
     
    import re
     
    line = "Cats are smarter than dogs";
     
    matchObj = re.match( r'dogs', line, re.M|re.I)
    if matchObj:
       print ("match --> matchObj.group() : ", matchObj.group())
    else:
       print ("No match!!")
     
    matchObj = re.search( r'dogs', line, re.M|re.I)
    if matchObj:
       print ("search --> matchObj.group() : ", matchObj.group())
    else:
       print ("No match!!")
    
    

    用的比较多的

    re.sub
     替换
     re.sub(pattern, repl, string, count=0, flags=0)
     前三为必选,
        pattern : 正则中的模式字符串。
        repl : 替换的字符串,也可为一个函数。
        string : 要被查找替换的原始字符串。
        count : 模式匹配后替换的最大次数,默认 0 表示替换所有的匹配。
        flags : 编译时用的匹配模式,数字形式。
        
        
    re.findall
     在字符串中找到正则表达式所匹配的所有子串,并返回一个列表
     re.finditer(pattern, string, flags=0)
              pattern	匹配的正则表达式
              string	要匹配的字符串。
    		  flags	标志位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等。参见:正则表达式 		   修饰符 - 可选标志
    		  
    re.split
    
    split 方法按照能够匹配的子串将字符串分割后返回列表,它的使用形式如下:
    
    re.split(pattern, string[, maxsplit=0, flags=0])
    
    
    
  • 相关阅读:
    1136 A Delayed Palindrome (algorithm reverse(ans.begin,ans.end))
    1141 PAT Ranking of Institutions PAT甲级
    最近点对 (迭代器访问数据)
    1146 Topological Order PAT 甲级
    1151 1151 LCA in a Binary Tree PAT 甲级
    jQuery的基本使用
    案例:移动端返回顶部效果
    移动端轮播图(原生JS写法)
    移动端特效
    本地存储
  • 原文地址:https://www.cnblogs.com/thenbz3/p/11534070.html
Copyright © 2020-2023  润新知