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"\d\d\d","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
来源:博客园
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

 

posted @ 2018-01-08 10:53  整合侠  阅读(2409)  评论(0编辑  收藏  举报