zoukankan      html  css  js  c++  java
  • Python3.x:正则 re.findall()的用法

    Python3.x:正则 re.findall()的用法

    概念:

     语法:findall(pattern, string, flags=0)

     说明:返回string中所有与pattern相匹配的全部字串,返回形式为数组)

    示例:

    # python3
    import re
    #示例1:查找全部r标识代表后面是正则的语句
    str_1 = re.findall(r"com","http://www.cnblogs.com/lizm166/p/8143231.html")
    print (str_1)
    #输出结果:['com']
    
    #示例2:符号^表示匹配以http开头的的字符串返回,
    str_2 = re.findall(r"^http","http://www.cnblogs.com/lizm166/p/8143231.html")
    print (str_2)
    # 输出结果:['http']
    
    #示例3:用$符号表示以html结尾的字符串返回,判断是否字符串结束的字符串
    str_3 = re.findall(r"html$","http://www.cnblogs.com/lizm166/p/8143231.html")
    print (str_3)
    # 输出结果:['html']
    
    # 示例4:[...]匹配括号中的其中一个字符
    str_4 = re.findall(r"[n,w]b","http://www.cnblogs.com/lizm166/p/8143231.html")
    print (str_4)
    # 输出结果:['nb']
    
    # 示例5:“d”是正则语法规则用来匹配0到9之间的数返回列表
    str_5 = re.findall(r"d","http://www.cnblogs.com/lizm166/p/8143231.html")
    str_6 = re.findall(r"ddd","http://www.cnblogs.com/lizm166/p/8143231.html")
    print (str_5)
    # 输出结果:['1', '6', '6', '8', '1', '4', '3', '2', '3', '1']
    print (str_6)
    # 输出结果:['166', '814', '323']
    
    # 示例6:小d表示取数字0-9,大D表示不要数字,也就是除了数字以外的内容返回
    str_7 = re.findall(r"D","http://www.cnblogs.com/lizm166/p/8143231.html")
    print (str_7)
    # 输出结果:['h', 't', 't', 'p', ':', '/', '/', 'w', 'w', 'w', '.', 'c', 'n', 'b', 'l', 'o', 'g', 's', '.', 'c', 'o', 'm', '/', 'l', 'i', 'z', 'm', '/', 'p', '/', '.', 'h', 't', 'm', 'l']
    
    # 示例7:“w”在正则里面代表匹配从小写a到z,大写A到Z,数字0到9
    str_8 = re.findall(r"w","http://www.cnblogs.com/lizm166/p/8143231.html")
    print (str_8)
    # 输出结果:['h', 't', 't', 'p', 'w', 'w', 'w', 'c', 'n', 'b', 'l', 'o', 'g', 's', 'c', 'o', 'm', 'l', 'i', 'z', 'm', '1', '6', '6', 'p', '8', '1', '4', '3', '2', '3', '1', 'h', 't', 'm', 'l']
    
    # 示例8:“W”在正则里面代表匹配除了字母与数字以外的特殊符号
    str_9 = re.findall(r"W","http://www.cnblogs.com/lizm166/p/8143231.html")
    print (str_9)
    # 输出结果:[':', '/', '/', '.', '.', '/', '/', '/', '.']

     对于上述示例中的代码可以改装(更加合理的编码行为),就拿示例4来改装:

    #定义正则规则
    re_cp = re.compile(r"[n,w]b")
    #匹配
    str_ = re.findall(re_cp,"http://www.cnblogs.com/lizm166/p/8143231.html")
    print (str_)
    # 输出结果:['nb']

    作者:整合侠
    链接:http://www.cnblogs.com/lizm166/p/8205085.html
    来源:博客园
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

  • 相关阅读:
    HDU4758 Walk Through Squares(AC自动机+状压DP)
    HIT2543 Stone IV(一定费用内的最大流)
    HIT2715 Matrix3(最小费用最大流)
    COGS738 [网络流24题] 数字梯形(最小费用最大流)
    HDU3157 Crazy Circuits(有源汇流量有上下界网络的最小流)
    ZOJ3229 Shoot the Bullet(有源汇流量有上下界网络的最大流)
    BZOJ 1834 [ZJOI2010]network 网络扩容(费用流)
    BZOJ 1475 方格取数(二分图最大点权独立集)
    BZOJ 4236 JOIOJI(前缀和)
    HZAU 1201 Friends(树形DP)
  • 原文地址:https://www.cnblogs.com/lizm166/p/8241583.html
Copyright © 2011-2022 走看看