標籤: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