【C#】字串有效轉成超連結

透過正規化表示式有效的判斷 RegularExpressionValidator,將含有Http(s)字串轉成HyperLink表示之

Aspx頁面(部份程式碼參考) : 置入一個標籤及一個按鈕
    <asp:Label ID="Label1" runat="server" Text="網址 http://blog.xuite.net 是嗎?"></asp:Label>          
         <br /><br /><br />  
    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="轉換" />  

CS程式碼(參考) : 
  if (Regex.Match(this.Label1.Text, @"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?") != Match.Empty)
     {           
        Response.Write("原始網址字串 : " + Regex.Match(this.Label1.Text, @"http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?").Value);
        this.Label1.Text = Regex.Replace(this.Label1.Text, @"(?<link>http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?)+", "<a href=\"${link}\">${link}</a>");
     }

畫面(初始化) :


畫面(按下按鈕後) :


留言

這個網誌中的熱門文章

【ASP】日期轉換(西元<-->民國)

【VB】使用NPOI元件來匯出Excel--DataTableToExcel

【SQL】符號切割字串變成多欄