这类嵌套正则如何写?通过id属性获得一个标签块

王集鹄 王集鹄 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
需求:就是通过id获得一个html标签块。

要处理的字符串:
<html>
<body>
<div id="div1">
<div id="div2" style="background:Red;">
<div id="div3">
<table id="table1">
<tr>
<td>
<div id="div4" style="width:100p
x"></div>
</td>
</tr>
</table>
</div>
</div>
<div id="div5">
<a href="http://www.csdn.net">csdn</a>
</div>
</div>
<img src="http://www.csdn.net/Images/logo_csdn.gif"/>
</body>
</html>


输入输出样例1
输入:"div1"
输出:
<div id="div1">
<div id="div2" style="background:Red;">
<div id="div3">
<table id="table1">
<tr>
<td>
<div id="div4" style="width:100p
x"></div>
</td>
</tr>
</table>
</div>
</div>
<div id="div5">
<a href="http://www.csdn.net">csdn</a>
</div>
</div>


输入输出样例2
输入:"div2"
输出:
        <div id="div2" style="background:Red;">
<div id="div3">
<table id="table1">
<tr>
<td>
<div id="div4" style="width:100p
x"></div>
</td>
</tr>
</table>
</div>
</div>


输入输出样例3
输入:"div3"
输出:
                <div id="div3">
<table id="table1">
<tr>
<td>
<div id="div4" style="width:100p
x"></div>
</td>
</tr>
</table>
</div>



输入输出样例4
输入:"table1"
输出:
                        <table id="table1">
<tr>
<td>
<div id="div4" style="width:100p
x"></div>
</td>
</tr>
</table>


调试代码:
目前只实现没有嵌套的匹配--"div4"
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string html = @"
<html>
<body>
<div id=""div1"">
<div id=""div2"" style=""background:Red;"">
<div id=""div3"">
<table id=""table1"">
<tr>
<td>
<div id=""div4"" style=""width:100px""></div>
</td>
</tr>
</table>
</div>
</div>
<div id=""div5"">
<a href=""http://www.csdn.net"">csdn</a>
</div>
</div>
<img src=""http://www.csdn.net/Images/logo_csdn.gif""/>
</body>
</html>";
Console.WriteLine(html);
string[] idList = { "div1", "div2", "div3", "div4", "table1" };

/* TODO : 这里发挥 */
string pattern = @"<([a-z]+)[^>]*\bid=(""|'){0}\2[^>]*></\1>";

foreach (string id in idList)
{
Match match = Regex.Match(html, string.Format(pattern, id),
RegexOptions.Singleline | RegexOptions.IgnoreCase);
Console.WriteLine("--------begin {0}--------", id);
if (match.Success)
Console.WriteLine(match.Value);
else
Console.WriteLine("o(╯□╰)o");
Console.WriteLine("--------end {0}--------", id);
}
Console.ReadKey();
}
}
}


[Quote=输出]
--------begin div1--------
o(╯□╰)o
--------end div1--------
--------begin div2--------
o(╯□╰)o
--------end div2--------
--------begin div3--------
o(╯□╰)o
--------end div3--------
--------begin div4--------
<div id="div4" style="width:100px"></div>
--------end div4--------
--------begin table1--------
o(╯□╰)o
--------end table1--------
[/Quote]
...全文

相关推荐

评论 99
收藏 已收藏
分享
返回顶部
王集鹄
C# 111,129 成员 642,538 内容