Python3.x:正则 re.findall()的用法
概念:
语法:findall(pattern, string, flags=0)
说明:返回string中所有与pattern相匹配的全部字串,返回形式为数组)
示例:
1# python3 2import re 3#示例1:查找全部r标识代表后面是正则的语句 4str_1 = re.findall(r"com","http://www.cnblogs.com/lizm166/p/8143231.html") 5print (str_1) 6#输出结果:['com'] 7 8#示例2:符号^表示匹配以http开头的的字符串返回, 9str_2 = re.findall(r"^http","http://www.cnblogs.com/lizm166/p/8143231.html") 10print (str_2) 11# 输出结果:['http'] 12 13#示例3:用$符号表示以html结尾的字符串返回,判断是否字符串结束的字符串 14str_3 = re.findall(r"html$","http://www.cnblogs.com/lizm166/p/8143231.html") 15print (str_3) 16# 输出结果:['html'] 17 18# 示例4:[...]匹配括号中的其中一个字符 19str_4 = re.findall(r"[n,w]b","http://www.cnblogs.com/lizm166/p/8143231.html") 20print (str_4) 21# 输出结果:['nb'] 22 23# 示例5:“d”是正则语法规则用来匹配0到9之间的数返回列表 24str_5 = re.findall(r"\d","http://www.cnblogs.com/lizm166/p/8143231.html") 25str_6 = re.findall(r"\d\d\d","http://www.cnblogs.com/lizm166/p/8143231.html") 26print (str_5) 27# 输出结果:['1', '6', '6', '8', '1', '4', '3', '2', '3', '1'] 28print (str_6) 29# 输出结果:['166', '814', '323'] 30 31# 示例6:小d表示取数字0-9,大D表示不要数字,也就是除了数字以外的内容返回 32str_7 = re.findall(r"\D","http://www.cnblogs.com/lizm166/p/8143231.html") 33print (str_7) 34# 输出结果:['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'] 35 36# 示例7:“w”在正则里面代表匹配从小写a到z,大写A到Z,数字0到9 37str_8 = re.findall(r"\w","http://www.cnblogs.com/lizm166/p/8143231.html") 38print (str_8) 39# 输出结果:['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'] 40 41# 示例8:“W”在正则里面代表匹配除了字母与数字以外的特殊符号 42str_9 = re.findall(r"\W","http://www.cnblogs.com/lizm166/p/8143231.html") 43print (str_9) 44# 输出结果:[':', '/', '/', '.', '.', '/', '/', '/', '.']
对于上述示例中的代码可以改装(更加合理的编码行为),就拿示例4来改装:
1#定义正则规则 2re_cp = re.compile(r"[n,w]b") 3#匹配 4str_ = re.findall(re_cp,"http://www.cnblogs.com/lizm166/p/8143231.html") 5print (str_) 6# 输出结果:['nb']
作者:整合侠
链接:http://www.cnblogs.com/lizm166/p/8205085.html
来源:博客园
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。