Regex提取網址、標題、圖片等一例(.Net Asp Javascript/Js)的實現

來源:互聯網
上載者:User

在一些抓取、過濾等情況下, Regex regular expression 的優勢是很明顯的。
例如,有如下的字串: 複製代碼 代碼如下:<li><a href="http://www.abcxyz.com/something/article/143.htm" title="FCKEditor高亮代碼外掛程式測試"><span class="article-date">[09/11]</span>FCKEditor高亮代碼外掛程式測試</a></li>

現在,需要提取 href 後面的網址,[]內的日期,和 連結的文字。
下面給出C#, ASP 和 Javascript 的實現方式
C#的實現 複製代碼 代碼如下:string strHTML = "<li><a \"href=http://www.abcxyz.com/something/article/143.htm\" title=\"FCKEditor高亮代碼外掛程式測試\"><span class=\"article-date\">[09/11]</span>FCKEditor高亮代碼外掛程式測試</a></li>";
string pattern = "http://([^\\s]+)\".+?span.+?\\[(.+?)\\].+?>(.+?)<";
Regex reg = new Regex( pattern, RegexOptions.IgnoreCase );
MatchCollection mc = reg.Matches( strHTML );
if (mc.Count > 0)
{
foreach (Match m in mc)
{
Console.WriteLine( m.Groups[1].Value );
Console.WriteLine( m.Groups[2].Value );
Console.WriteLine( m.Groups[3].Value );
}
}

ASP的實現 複製代碼 代碼如下:<%
Dim str, reg, objMatches
str = "<li><a href=""http://localhost/Z-Blog18/article/143.htm"" title=""FCKEditor高亮代碼外掛程式測試""><span class=""article-date"">[09/11]</span>FCKEditor高亮代碼外掛程式測試</a></li>"
Set reg = new RegExp
reg.IgnoreCase = True
reg.Global = True
reg.Pattern = "http://([^\s]+)"".+?span.+?\[(.+?)\].+?>(.+?)<"
Set objMatches = reg.Execute(str)
If objMatches.Count > 0 Then
Response.Write("網址:")
Response.Write(objMatches(0).SubMatches(0))
Response.Write("<br>")
Response.Write("日期:")
Response.Write(objMatches(0).SubMatches(1))
Response.Write("<br>")
Response.Write("標題:")
Response.Write(objMatches(0).SubMatches(2))
End If
%>

Javascript的實現 複製代碼 代碼如下:<script type="text/javascript">
var str = '<li><a href="http://localhost/Z-Blog18/article/143.htm" title="FCKEditor高亮代碼外掛程式測試"><span class="article-date">[09/11]</span>FCKEditor高亮代碼外掛程式測試</a></li>';
var pattern = /http:\/\/([^\s]+)".+?span.+?\[(.+?)\].+?>(.+?)</gi;
var mts = pattern.exec(str);
if (mts != null)
{
alert(mts[1]);
alert(mts[2]);
alert(mts[3]);
alert(mts[4]);
}
</script>

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.