[轉] Url 轉 Link 的 C# Regex

來源:互聯網
上載者:User

標籤:style   blog   http   io   color   ar   os   使用   sp   

網上關於 Url 轉連結( href )的Regex一搜一大堆,但真正好用的沒幾個。

後來在 Matthew O‘Riordan 的 Blog 上發現一個很好用的Regex,是用 Javascript 寫的,代碼如下:

 1   (  // brackets covering match for protocol (optional) and domain 2     ([A-Za-z]{3,9}:(?:\/\/)?) // match protocol, allow in format http:// or mailto: 3     (?:[\-;:&=\+\$,\w][email protected])?    // allow [email protected] for email addresses 4     [A-Za-z0-9\.\-]+          // anything looking at all like a domain, non-unicode domains 5     |// or instead of above 6     (?:www\.|[\-;:&=\+\$,\w][email protected]) // starting with [email protected] or www. 7     [A-Za-z0-9\.\-]+            // anything looking at all like a domain 8   ) 9   ( // brackets covering match for path, query string and anchor10     (?:\/[\+~%\/\.\w\-]*)    // allow optional /path11     ?\??(?:[\-\+=&;%@\.\w]*) // allow optional query string starting with ? 12     #?(?:[\.\!\/\\\w]*)      // allow optional anchor #anchor13   )? // make URL suffix optional

 

針對我們的使用情境(只對 http 或 https 開頭的 Url進行轉換)簡化了一下,並用 C# 寫出:

 1 public static class ContentFormatter 2 { 3     private static readonly Regex Url_To_Link = new Regex(@"(?<url> 4         (https?:(?:\/\/)?)        # match protocol, allow in format http:// or https:// 5         [A-Za-z0-9\.\-]+          # anything looking at all like a domain, non-unicode domains         6         (                         # brackets covering match for path, query string and anchor 7         (?:\/[\+~%\/\.\w\-]*)?    # allow optional /path 8         \??(?:[\-\+=&;%@\.\w]*?)  # allow optional query string starting with ?  9         \#?(?:[\.\!\/\\\w\-]*)      # allow optional anchor #anchor10         )?                        # make URL suffix optional11         )",12         RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace,13         TimeSpan.FromMilliseconds(100));14 15     public static string UrlToLink(string text)16     {17         if (string.IsNullOrEmpty(text)) return string.Empty;18 19         return Url_To_Link.Replace(text, "<a href=\"${url}\" target=\"_blank\">${url}</a>");20     }21 }
 

[轉] Url 轉 Link 的 C# Regex

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.