利用正则查找html代码中的ID值

笨鸟开始飞的博客 / 2023-08-23 / 原文

直接上代码:

 1           string rule = " id='(?<value>.*?)'";
 2                 System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(rule);
 3                 //html代码
 4                 string htmlCode = "<span id='726577'>&nbsp;&nbsp;<input type='hidden' name='filename' value='726577' /><img src=\"/Content/Images/fj_img.gif\" align=\"middle\" /><a href=\"/OMSFile/Download/?Id=qyvHSsazPfkopjhqRqTuDMIqvJ3dYSh6FTDwLbRFiaiKmKMdzz3RBfu/OGMu%2Ba9t2bSzvRpFZLGbE9hhQFs/x/KVsOJz%2BmYKZoPIJCHLPhZDS3xheNiU0eKb1aZ6If/Dhjaqjz/lVR/g7GRCemwzyS%2BEfj8Vq8PJOfxCMIWFBDs=\">aaa.doc</a>&nbsp;<img src='/ContentV2/Images/emp/del_fujian_01.png' align='middle' title='删除' onclick='deletefile(726577);' onmouseover=\"this.src='/ContentV2/Images/emp/del_fujian_02.png'\"  onmouseout=\"this.src='/ContentV2/Images/emp/del_fujian_01.png'\" /></span>";
 5                 //匹配
 6                 System.Text.RegularExpressions.MatchCollection matchCollection = regex.Matches(htmlCode);
 7                 if (matchCollection != null)
 8                 {
 9                     //循环输出每个ID的值
10                     foreach (System.Text.RegularExpressions.Match match in matchCollection)
11                     {
12                         var value = match.Groups["value"].Value;
13                     }
14                 }