日期:2014-05-18  浏览次数:20497 次

怎样用正则表达式,获取html中源代码指定的部分
假设我已获得了网页的源代码,怎么写正则表达式,获取指定id 的div 部分的源代码,如获取下面的红色字体
---------------------------------
<div id="test">
testString
</div>
  <div>
  <asp:DataList id="DataList1"
  BorderColor="black"
  CellPadding="1"
  CellSpacing="4" HorizontalAlign="Center"
  RepeatColumns="4"
  RepeatLayout="Table"
  runat="server" ShowFooter="true" ShowHeader="true"
  width="100%">
  <HeaderTemplate>
  <table style="width: 100%">
  <tr>
  <td style="width:50%">
  地区编号</td>
  <td style="width:50%" align="left">
  地区名称</td>
  </tr>
  </table>
  </HeaderTemplate>
  <ItemTemplate>
  </ItemTemplate>
  </asp:DataList>  
  <input id="Button1" type="button" value="button" language="javascript" onclick="return Button1_onclick()" /></div>

  </form>
</body>
</html>

------解决方案--------------------

try:
(\<div\s+id="test"\>[^</div>]*?\<\/div\>)


------解决方案--------------------
C# code

using System.Text.RegularExpressions;

Regex re = new Regex(@"(?<content><div\s*id=""?test""?\s*>[\s\S]*?</div>)");
Match m = re.Match(str);

m.Groups["content"];

------解决方案--------------------
你去看看正则表达式怎么使用吧