Pyhton_45正则表达式之match以及分组

一、正则

正则表达式就是re模块,要先引入  re  模块

re主要的功能:

import re
re.match()#从头匹配 匹配一个 从字符串的开头匹配
#无分组
testss='hello alex bcd alex dd acd 19'
r=re.match('h\w+',testss) #如果用到 ‘a\w’ 则会匹配不到任何内容
print (r.group())#hello 获取匹配到的所有结果
print (r.groups())#() 获取模型中匹配到的分组结果
print (r.groupdict())#{} 获取模型中匹配到的分组结果
#有分组  提取配成功的指定内容 先匹配一长串,再匹配一长串中的一小节
testss='helloss alex bcd alex dd acd 19'
r=re.match('(h)(\w+)',testss)
print (r.group())#helloss 获取匹配到的所有结果
print (r.groups())#('h','elloss') 获取模型中匹配到的分组结果
print (r.groupdict())#{} 获取模型中匹配到的分组结果

#有分组 提取配成功的指定内容 先匹配一长串,再匹配一长串中的一小节
testss='helloss alex bcd alex dd acd 19'
r=re.match('h(\w+)',testss)
print (r.group())#helloss 获取匹配到的所有结果
print (r.groups())#('elloss') 获取模型中匹配到的分组结果
print (r.groupdict())#{} 获取模型中匹配到的分组结果

#有分组  提取配成功的指定内容 先匹配一长串,再匹配一长串中的一小节
testss='helloss alex bcd alex dd acd 19'
r=re.match('(?P<n1>h)(?P<n2>\w+)',testss) #?P<n1>这个就是在说是字典的key
print (r.group())#helloss 获取匹配到的所有结果
print (r.groups())#('h','elloss') 获取模型中匹配到的分组结果
print (r.groupdict())#{'n1': 'h', 'n2': 'elloss'} 获取模型中匹配到的分组结果

re.split()
re.search()#在整个字符串的全局里匹配第一个出现的合法的对象 匹配一个
re.findall()#将匹配到的东西全部放到列表中
re.sub()
re.finditer()


 

 

二、

 

posted on 2018-03-28 17:18  JuGooLar  阅读(177)  评论(0编辑  收藏  举报

导航