日期:2014-05-17  浏览次数:20915 次

提取嵌套子标签内容的正则表达式
最近在学习用VB的XMLHTTP写爬虫,在分析网页源代码的时候遇到了这样一个问题:某些HTML标签是允许嵌套的,例如<DIV>;我现在的需求是获取被嵌套的子标签直接的内容,为此,我花了好久(本人接触正则表达式不久,属于菜鸟级的水平)写并测试了一个表达式,如下面几个函数所示:
'返回执行正则表达式后的匹配集合
Public Function RegExp(src As String, ptrn As String, Optional ic As Boolean = True, Optional gb As Boolean = True) As MatchCollection
Dim re As RegExp
    Set re = New RegExp
    With re
        .Pattern = ptrn
        .Global = gb
        .IgnoreCase = ic
    End With
    Set RegExp = re.Execute(src)
    Set re = Nothing
End Function
'非贪婪地获取成对出现的标签
Public Function GetSingleTagPair(tag As String, src As String) As MatchCollection
    Set GetSingleTagPair = RegExp(src, "<" & tag & ".*?>([\s\S](?!<" & tag & ".*?>))*?(</" & tag & ">)")
End Function

红色部分就是我写的表达式。

我的测试文本是:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>图书馆 v4.0 书目检索系统  我的图书馆</title>
<link type="text/css" rel="stylesheet" href="../tpl/css/base.css">
<link type="text/css" rel="stylesheet" href="../tpl/css/main.css">
<script src="../tpl/js/prototype.js"></script>
<script src="../tpl/js/highlighter.js"></script>
</head>

<body>
<body>
<div id="header">
   <div id="logo"><img src="../tpl/images/logo.jpg" width="76" height="44" /></div>
   <h1 class="font_30px">图书馆书目检索系统</h1>
   <div id="navlogin" > 
              <a href="../reader/book_shelf.php">我的书架</a> | <a href="../reader/search_hist.php">我的检索历史</a> 
   </div>
</div>

<div id="menu">
    <ul>
      <li><a href="../opac/search.php">书目检索</a></li><li><a href="../opac/cls_browsing.php">分类浏览</a></li><li><a href="../opac/peri_nav_e.php">期刊导航</a></li><li><a href="../opac/newbook_cls_browse.php">新书通报</a></li><li><a href="../opac/virtual_shelf.php">公共书架</a></li><li><a href="../info/info_guide.php">信息发布</a></li><li><a href="../asord/asord_redr.php">读者荐购</a></li><li><a href="../reader/redr_cust_result.php"><b>我的图书馆</b></a></li>    </ul>
    <div style="color:#FFF; float:right;padding:5px 20px 0 0px">
     <img src="../tpl/images/icon_login.