028-86922220

建站动态

根据您的个性需求进行定制 先人一步 抢占小程序红利时代

python中re模块简析

re的分组功能

python的re模块有一个分组功能。所谓的分组就是去已经匹配到的内容里面再筛选出需要的内容,相当于二次过滤。

创新互联提供网站设计制作、成都做网站、网页设计,成都品牌网站建设1元广告等致力于企业网站建设与公司网站制作,十多年的网站开发和建站经验,助力企业信息化建设,成功案例突破上千,是您实现网站建设的好选择.

实现分组靠圆括号(),而获得分组的内容靠的是group(),groups(),groupdict()方法。

re模块里的几个重要方法在分组上,有不同的表现形式,需要区别对待。

re实例

match()方法

不分组时的情况:

import re

origin = "hasdfi123123safd"
# 不分组时的情况
r = re.match("h\w+", origin)
print(r.group())         # 获取匹配到的整体结果
print(r.groups())        # 获取模型中匹配到的分组结果元组
print(r.groupdict())     # 获取模型中匹配到的分组中所有key的字典

结果:
hasdfi123123safd
()
{}

有分组的情况(注意圆括号!)

import re

origin = "hasdfi123123safd123"
# 有分组
r = re.match("h(\w+).*(?P\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\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', line, 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 (.*?) .*', line, 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!!"

说明⚠️:关于正则表达式r'(.*) are (.*?) .*'

参考文档


本文题目:python中re模块简析
URL地址:http://www.tsicrk.com/article/ghighj.html

其他资讯

让你的专属顾问为你服务

4.5080s