Python的学习笔记DAY10---关于正则表达式

来源:互联网 发布:网络销售红酒骗局 编辑:程序博客网 时间:2024/05/17 02:20

        正则表达式用来匹配查找文本和数据,简单的说,是一些由字符和特殊符号组成的字符串,描述了模式的重复或者表述多个字符。其能按照某种模式匹配一系列有相似特征的字符串。

        Python中的正则表达式通过re模块来支持。

        首先是元字符。正则表达式语言由两种基本字符类型组成:原义(正常)文本字符和元字符。元字符使正则表达式具有处理能力。所谓元字符就是指那些在正则表达式中具有特殊意义的专用字符,可以用来规定其前导字符(即位于元字符前面的字符)在目标对象中的出现模式。

        常用的元字符有  “.”,“|”,“^”,“$”,“\”等,使用举例如下:

#.的使用ma = re.match(r'...','0a!')ma.group()>>>'0a!'ma = re.match(r'...','0a\n')ma.group()>>>AttributeError: 'NoneType' object has no attribute 'group'

“.”可以匹配除了换行之外的任意字符,上面代码中的“...”匹配到了“0a!”三个字符,而在下面的代码中最后一个是换行,所以没有匹配到,所以ma是一个NoneType。

#|的使用ma = re.match(r'...|..','0a\n')ma.group()>>>'0a'
“a|b”表示匹配正则表达式a或者b,上面的例子里成功的匹配到了字符

#[]的使用ma = re.match(r'[ab]','a')ma.group()>>>'a'ma = re.match(r'[ab]','b')ma.group()>>>'b'ma = re.match(r'[a-zA-Z0-9][a-zA-Z0-9][a-zA-Z0-9]','fF6')ma.group()>>>'fF6'
“[...]”用来匹配字符集,“[]”里表示一个范围,可以指定,也可以用“-”相连表示范围。

# \d \D \s \S \w \W的使用ma = re.match(r'\d\d\D\D','12a$')ma.group()>>>'12a$'ma = re.match(r'\d\d\D\D','a$12')ma.group()>>>AttributeError: 'NoneType' object has no attribute 'group'ma = re.match(r'\s\s\S\S','  ss')ma.group()>>>'  ss'ma = re.match(r'\s\s\S\S','ss  ')ma.group()>>>AttributeError: 'NoneType' object has no attribute 'group'ma = re.match(r'\w\w\W\W','a1  ')ma.group()>>>'a1  'ma = re.match(r'\w\w\W\W','  a1')ma.group()>>>AttributeError: 'NoneType' object has no attribute 'group'
“\d”来表示一个数字,“\D”表示一个非数字,“\s”表示一个空白,“\S”表示一个非空白,“\w“表示一个单词字符,”\W”表示非单词字符。

#* + ? {}的使用ma = re.match(r'.*','')ma.group()>>>''ma = re.match(r'.*','aaaaaaaaaaa')ma.group()>>>'aaaaaaaaaaa'ma = re.match(r'.+','a')ma.group()>>>'a'ma = re.match(r'.+','aaaa')ma.group()>>>'aaaa'ma = re.match(r'.?','a')ma.group()>>>'a'ma = re.match(r'.?','')ma.group()>>>''ma = re.match(r'.{3,5}','1234')ma.group()>>>'1234'ma = re.match(r'.{3,5}','123456789')ma.group()>>>'12345'
如上代码显示*表示一个字符重复0-N次,+代表重复1-N次,?表示重复0-1次,{a,b}表示重复a-b次。
#^ $ 的使用ma = re.match(r'^a..','abc')ma.group()>>>'abc'ma = re.match(r'^a..','bac')ma.group()>>>AttributeError: 'NoneType' object has no attribute 'group'ma = re.match(r'..c$','abc')ma.group()>>>'abc'ma = re.match(r'..c$','acb')ma.group()>>>AttributeError: 'NoneType' object has no attribute 'group'

^表示字符串以^后面的字符作为开头,$表示字符串以$前面的字符结尾。

        以上的正则表达式均是使用match方法来匹配的,match是从头开始匹配,正则表达式的常用方法有很多,例如serach和findall。代码举例如下:

#search 和 findall 的使用str = 'a100,b200,c300,d400'ma = re.search(r'\d+',str)ma.group()>>>'100'ma = re.findall(r'\d+',str)ma>>>['100', '200', '300', '400']

search用来在字符串中搜索对应的子字符串,搜索到第一个停止,findall用来搜索所有符合规定的字符串并返回一个列表。

        sub和split方法:

#sub 和 spilt 的使用str = 'abc1234def'm = re.sub(r'\d+','5678',str)m>>>'abc5678def'str = 'name:苍井空 松岛枫 泷泽萝拉,小泽玛利亚're.split(r':| |,',str)>>>['name', '苍井空', '松岛枫', '泷泽萝拉', '小泽玛利亚']
sub用来将查找到的字符串替换,spilt用于将字符串分割。


0 0
原创粉丝点击