python中使用re的基本流程

来源:互联网 发布:ubuntu进入root文件夹 编辑:程序博客网 时间:2024/05/21 23:46

1. 通过re.compile生成正则表达式对象

2. 调用正则表达式对象的match或者search方法生成match或search对象

3. 判断match或search对象对否为None,如果不为None,通过group方法获取分组匹配字符串。

注意: 如果不做判断的话,当匹配失败调用group方法会报异常(AttributeError: 'NoneType' object has no attribute 'group')退出。


$cat html<td width="15%" rowspan="2" class="t0" style="background:#f4f7fc;"><a title="农历六月十九">6日星期一</a></td><td width="12%" style="background:#f4f7fc;">白天</td><b>高温 <strong>33℃</strong></b><td style="background:#f4f7fc;">夜间</td><span>低温 <strong>25℃</strong></span>$cat 1.py#!/usr/bin/pythonimport reresult=""file = open("html")# 将正则表达式编译成Pattern对象 p1 = re.compile(">([^<]*)</a>")p2 = re.compile(">([^<]*)</td>")p3 = re.compile(">([^<]*)</strong>")for line in file:    #使用Pattern匹配文本,获得匹配结果    s1 = p1.search(line)    s2 = p2.search(line)    s3 = p3.search(line)        #匹配失败时将返回None,匹配成功时试用group来获取分组信息    if s1:        result = s1.group(1) + "\n"    elif s2:        result += s2.group(1) + " "    elif s3:        result += s3.group(1) + "\n" print result

原创粉丝点击