本篇主要介绍正则表达式中的元字符,本人水平有限,难免出现错误,欢迎指正。
1、匹配单个数字
示例:
importre
#匹配0,1,2,3
print(re.findall(r"[0123]","_z0hi shu 61fen x3789i%!"))
#匹配0,1,2,3,4,5,6,7
print(re.findall("[0-7]","_z0hi shu 61fen x3789i%!"))
#匹配所有数字
print(re.findall("\d","_z0hi shu 61fen x3789i%!"))
#匹配除0,1,2,3,4,5,6,7以外的所有字符
print(re.findall("[^0-7]","_z0hi shu 61fen x3789i%!"))
#匹配非数字字符
print(re.findall("\D","_z0hi shu 61fen x3789i%!"))
输出:
['0', '1', '3']
['0', '6', '1', '3', '7']
['0', '6', '1', '3', '7', '8', '9']
['_', 'z', 'h', 'i', ' ', 's', 'h', 'u', ' ', 'f', 'e', 'n', ' ', 'x', '8', '9', 'i', '%', '!']
['_', 'z', 'h', 'i', ' ', 's', 'h', 'u', ' ', 'f', 'e', 'n', ' ', 'x', 'i', '%', '!']
2、匹配单个字符
示例:
importre
#匹配除换行符以外的任意字符
print(re.findall(r".","_z0hi shu 61fen x3789i%!"))
#匹配'z','s','u'中任意一个字符
print(re.findall("[zsu]","_z0hi shu 61fen x3789i%!"))
#匹配x,y,z中任意一个字符
print(re.findall("[x-z]","_z0hi shu 61fen x3789i%!"))
#匹配X,Y,Z中任意一个字符
print(re.findall("[X-Z]","_z0hi shu 61fen x3789i%!"))
#匹配0,1,2,3,a,b,c中任意一个字符
print(re.findall("[0-3a-c]","_z0hi shu 61fen x3789i%!"))
#匹配数字,字母和下划线
print(re.findall(r"\w","_z0hi shu 61fen x3789i%!"))
#匹配除了z,s,u这几个字母以外的所有字符
print(re.findall("[^zsu]","_z0hi shu 61fen x3789i%!"))
#匹配非数字,字母和下划线
print(re.findall("\W","_z0hi shu 61fen x3789i%!"))
#匹配任意的空白符
print(re.findall("\s","_z0hi shu 61fen x3789i%!"))
#匹配任意的非空白符
print(re.findall("\S","_z0hi shu 61fen x3789i%!"))
输出:
['_', 'z', '0', 'h', 'i', ' ', 's', 'h', 'u', ' ', '6', '1', 'f', 'e', 'n', ' ', 'x', '3', '7', '8', '9', 'i', '%', '!']
['z', 's', 'u']
['z', 'x']
[]
['0', '1', '3']
['_', 'z', '0', 'h', 'i', 's', 'h', 'u', '6', '1', 'f', 'e', 'n', 'x', '3', '7', '8', '9', 'i']
['_', '0', 'h', 'i', ' ', 'h', ' ', '6', '1', 'f', 'e', 'n', ' ', 'x', '3', '7', '8', '9', 'i', '%', '!']
[' ', ' ', ' ', '%', '!']
[' ', ' ', ' ']
['_', 'z', '0', 'h', 'i', 's', 'h', 'u', '6', '1', 'f', 'e', 'n', 'x', '3', '7', '8', '9', 'i', '%', '!']
领取专属 10元无门槛券
私享最新 技术干货