python中re模块简析
re的分组功能
python的re模块有一个分组功能。所谓的分组就是去已经匹配到的内容里面再筛选出需要的内容,相当于二次过滤。 实现分组靠圆括号(),而获得分组的内容靠的是group(),groups(),groupdict()方法。 re模块里的几个重要方法在分组上,有不同的表现形式,需要区别对待。 re实例match()方法不分组时的情况:import re origin = "hasdfi123123safd" # 不分组时的情况 r = re.match("hw+",origin) print(r.group()) # 获取匹配到的整体结果 print(r.groups()) # 获取模型中匹配到的分组结果元组 print(r.groupdict()) # 获取模型中匹配到的分组中所有key的字典 结果: hasdfi123123safd () {} 有分组的情况(注意圆括号!)import re origin = "hasdfi123123safd123" # 有分组 r = re.match("h(w+).*(?P<name>d)$",origin) print(r.group()) # 获取匹配到的整体结果 print(r.group(1)) # 获取匹配到的分组1的结果 print(r.group(2)) # 获取匹配到的分组2的结果 print(r.groups()) # 获取模型中匹配到的分组结果元组 print(r.groupdict()) # 获取模型中匹配到的分组中所有key的字典 执行结果: hasdfi123123safd123 asdfi123123safd12 3 (‘asdfi123123safd12‘,‘3‘) {‘name‘: ‘3‘} 说明??:
search()方法有分组的情况:import re origin = "sdfi1ha23123safd123" # 注意这里对匹配对象做了下调整 # 有分组 r = re.search("h(w+).*(?P<name>d)$",origin) print(r.group()) print(r.group(0)) print(r.group(1)) print(r.group(2)) print(r.groups()) print(r.groupdict()) 执行结果: ha23123safd123 ha23123safd123 a23123safd12 3 (‘a23123safd12‘,‘3‘) {‘name‘: ‘3‘} 说明??:表现得和match()方法基本一样。 match()方法与search()方法区别re.match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None;而re.search匹配整个字符串,直到找到一个匹配。 举例如下: #!/usr/bin/python import re line = "Cats are smarter than dogs"; matchObj = re.match( r‘dogs‘,line,re.M|re.I) if matchObj: print "match --> matchObj.group() : ",matchObj.group() else: print "No match!!" matchObj = re.search( r‘dogs‘,re.M|re.I) if matchObj: print "search --> matchObj.group() : ",matchObj.group() else: print "No match!!" 以上代码执行结果如下: No match!! search --> matchObj.group() : dogs 扩展正则表达式实例: #!/usr/bin/python import re line = "Cats are smarter than dogs" matchObj = re.match( r‘(.*) are (.*?) .*‘,re.M|re.I) if matchObj: print "matchObj.group() : ",matchObj.group() print "matchObj.group(1) : ",matchObj.group(1) print "matchObj.group(2) : ",matchObj.group(2) else: print "No match!!" 说明??:关于正则表达式
参考文档
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |