实例分析js和C#中使用正则表达式匹配a标签
废话不多说,都在代码中,直接上
JS代码:
<html>
<head>
<scriptlanguage="javascript">
vara='<P><Ahref=\'~abc/ccg/ab.jpg\'width="3">文字</A><Awidth="4"style="color:#ddd;font-weight:bold;"mm_href="http:www.baidu.com" href="http://bbs.cn.yimg.com/user_img/200701/31/soso1.jpg"mce_href="http://bbs.cn.yimg.com/user_img/200701/31/jisuanji986_117025184198149.jpg">cc</A>href="www.baidu.com"cbas<span>cchref</span>1<addhref="ccc" <Awidth="5"href="http://bbs.cn.yimg.com/user_img/200701/31/soso2.jpg"mce_href="http://bbs.cn.yimg.com/user_img/200701/31/cc.jpg"></A></P>';
varb=/<a([\s]+|[\s]+[^<>]+[\s]+)href=(\"([^<>"\']*)\"|\'([^<>"\']*)\')[^<>]*>/gi;
vars=a.toLowerCase().match(b);
alert(s.length);
for(vari=0;i<s.length;i++)
{
varss=s[i].toLowerCase().match(b);
alert(RegExp.$3+RegExp.$4);
}
</script>
</head>
<body>
</body>
</html>
C#代码:
stringhtml="<P><Ahref='~abc/ccg/ab.jpg'height=\"4\"width='3'>文字</A><Awidth=\"4\"style=\"color:#ddd;font-weight:bold;\"mm_href=\"http:www.baidu.com\" href=\"http://bbs.cn.yimg.com/user_img/200701/31/soso1.jpg\"mce_href=\"http://bbs.cn.yimg.com/user_img/200701/31/jisuanji986_117025184198149.jpg\">cc</A>href=\"www.baidu.com\"cbas<span>cchref</span> 1<adfhref=\"cc\" <Awidth=\"5\"href=\"http://bbs.cn.yimg.com/user_img/200701/31/soso2.jpg\"mce_href=\"http://bbs.cn.yimg.com/user_img/200701/31/cc.jpg\"></A></P>";
Regexreg=newRegex("<a([\\s]+|[\\s]+[^<>]+[\\s]+)href=(\"(?<href>[^<>\"']*)\"|'(?<href>[^<>\"']*)')[^<>]*>",RegexOptions.IgnoreCase);
MatchCollectionmatchCollection=reg.Matches(html);
MessageBox.Show(matchCollection.Count.ToString());
foreach(MatchmatchinmatchCollection)
{
MessageBox.Show(match.Groups["href"].ToString());
}
小伙伴们是否了解了js及C#中使用正则表达式的异同点呢?有疑问的请留言,大家共同讨论。