在實際開發中,需要用到的資料在url中,因此就需要我們來擷取到url中有用的資訊,涉及到查詢、添加、修改、刪除等操作,下面我們就具體來瞭解一下。
1.簡單一實例
目前常用Url操作,查詢、添加、修改、刪除連結參數,重構產生連結等功能。
//string url = "http://www.gongjuji.net:8081";//string url = "http://www.gongjuji.net/";//string url = "http://www.gongjuji.net/abc";// string url = "http://www.gongjuji.net/abc/1234.html";string url = "http://www.gongjuji.net/abc/1234.html?name=張三&age=1234#one#two";//string url = "http://www.gongjuji.net/abc/1234.html?name=&age=#one#two";//string url = "/abc/123.html?name=張三&age=1234#one#two";// string url = "https://mp.weixin.qq.com/debug/cgi-bin/apiinfo?t=index&type=%E7%94%A8%E6%88%B7%E7%AE%A1%E7%90%86&form=%E8%8E%B7%E5%8F%96%E5%85%B3%E6%B3%A8%E8%80%85%E5%88%97%E8%A1%A8%E6%8E%A5%E5%8F%A3%20/user/get";UrlAnalyze _url = new UrlAnalyze(url);JObject obj = JObject.FromObject(_url);Console.WriteLine(obj);//添加或修改參數_url.AddOrUpdateSearch("page", "2");_url.AddOrUpdateSearch("name", "李四");//重建連結參數Console.WriteLine(_url.GetUrl());Console.WriteLine(_url.GetUrl(true));
2、執行個體:
識別字串中的url
//string source = "工具集:http://www.gongjuji.net";string source = @"工具集: http://www.gongjuji.net 愛漢字:http://hanzi.tianma3798.cn"; List<string> result = UrlAnalyze.GetUrlList(source);foreach (var item in result){ Console.WriteLine(item);}//替換成a標籤string result2 = UrlAnalyze.ReplaceToA(source);Console.WriteLine(result2);</string>
屬性和部分功能模仿了Node.js的url模組
原始碼定義:
/// <summary>/// Url地址的格式化和反格式化/// </summary>public class UrlAnalyze{ /// <summary> /// 協議名稱 /// </summary> public string Protocol { get; set; } /// <summary> /// 是否以反斜線結尾 /// </summary> public bool Slashes { get; set; } /// <summary> /// 驗證資訊,暫時不使用 /// </summary> public string Auth { get; set; } /// <summary> /// 全小寫主機部分,包括連接埠 /// </summary> public string Host { get { if (this.Port == null) return this.HostName; return string.Format("{0}:{1}", this.HostName, this.Port); } } /// <summary> /// 連接埠,為空白時http預設是80 /// </summary> public int? Port { get; set; } /// <summary> /// 小寫主機部分 /// </summary> public string HostName { get; set; } /// <summary> /// 頁面錨點參數部分 #one#two /// </summary> public string Hash { get; set; } /// <summary> /// 連結查詢參數部分(帶問號) ?one=1&two=2 /// </summary> public string Search { get; set; } /// <summary> /// 路徑部分 /// </summary> public string PathName { get; set; } /// <summary> /// 路徑+參數部分(沒有錨點) /// </summary> public string Path { get { if (string.IsNullOrEmpty(this.Search)) return this.PathName; return PathName + Search; } } /// <summary> /// 轉碼後的原連結 /// </summary> public string Href { get; set; } /// <summary> /// 參數的key=value 列表 /// </summary> private Dictionary<string, string=""> _SearchList = null; #region 初始化處理 /// <summary> /// 空初始化 /// </summary> public UrlAnalyze() { _SearchList = new Dictionary<string, string="">(); } /// <summary> /// 初始化處理 /// </summary> ///<param name="url">指定相對或絕對連結 public UrlAnalyze(string url) { //1.轉碼操作 this.Href = HttpUtility.UrlDecode(url); InitParse(this.Href); //是否反斜線結尾 if (!string.IsNullOrEmpty(PathName)) this.Slashes = this.PathName.EndsWith("/"); //初始化參數列表 _SearchList = GetSearchList(); } /// <summary> /// 將字串格式化成對象時初始化處理 /// </summary> private void InitParse(string url) { //判斷是否是指定協議的絕對路徑 if (url.Contains("://")) { // Regex reg = new Regex(@"(\w+):\/\/([^/:]+)(:\d*)?([^ ]*)"); Regex reg = new Regex(@"(\w+):\/\/([^/:]+)(:\d*)?(.*)"); Match match = reg.Match(url); //協議名稱 this.Protocol = match.Result("$1"); //主機 this.HostName = match.Result("$2"); //連接埠 string port = match.Result("$3"); if (string.IsNullOrEmpty(port) == false) { port = port.Replace(":", ""); this.Port = Convert.ToInt32(port); } //路徑和查詢參數 string path = match.Result("$4"); if (string.IsNullOrEmpty(path) == false) InitPath(path); } else { InitPath(url); } } /// <summary> /// 字串url格式化時,路徑和參數的初始化處理 /// </summary> ///<param name="path"> private void InitPath(string path) { Regex reg = new Regex(@"([^#?& ]*)(\??[^#]*)(#?[^?& ]*)"); Match match = reg.Match(path); //路徑和查詢參數 this.PathName = match.Result("$1"); this.Search = match.Result("$2"); this.Hash = match.Result("$3"); } #endregion #region 參數處理 /// <summary> /// 擷取當前參數解析結果字典列表 /// </summary> /// <returns></returns> public Dictionary<string, string=""> GetSearchList() { if (_SearchList != null) return _SearchList; _SearchList = new Dictionary<string, string="">(); if (!string.IsNullOrEmpty(Search)) { Regex reg = new Regex(@"(^|&)?(\w+)=([^&]*)", RegexOptions.Compiled); MatchCollection coll = reg.Matches(Search); foreach (Match item in coll) { string key = item.Result("$2").ToLower(); string value = item.Result("$3"); _SearchList.Add(key, value); } } return _SearchList; } /// <summary> /// 擷取查詢參數的值 /// </summary> ///<param name="key">鍵 /// <returns></returns> public string GetSearchValue(string key) { return _SearchList[key]; } /// <summary> /// 添加參數key=value,如果值已經存在則修改 /// </summary> ///<param name="key">鍵 ///<param name="value">值 /// <returns></returns> public void AddOrUpdateSearch(string key, string value, bool Encode = false) { if (Encode) value = HttpUtility.UrlEncode(value); //判斷指定索引值是否存在 if (_SearchList.ContainsKey(key)) { _SearchList[key] = value; } else { _SearchList.Add(key, value); } } /// <summary> /// 刪除指定key 的索引值對 /// </summary> ///<param name="key">鍵 public void Remove(string key) { if (_SearchList.Any(q => q.Key == key)) _SearchList.Remove(key); } /// <summary> /// 擷取錨點列表 /// </summary> /// <returns></returns> public List<string> GetHashList() { List<string> list = new List<string>(); if (!string.IsNullOrEmpty(Hash)) { list = Hash.Split('#').Where(q => string.IsNullOrEmpty(q) == false) .ToList(); } return list; } #endregion /// <summary> /// 擷取最終url地址, /// 對參數值就行UrlEncode 編碼後,有可能和原連結不相同 /// </summary> /// <returns></returns> public string GetUrl(bool EncodeValue = false) { StringBuilder builder = new StringBuilder(); if (!string.IsNullOrEmpty(Protocol)) { //如果有協議 builder.Append(Protocol).Append("://"); } //如果有主機標識 builder.Append(Host); //如果有目錄和參數 if (!string.IsNullOrEmpty(PathName)) { string pathname = PathName; if (pathname.EndsWith("/")) pathname = pathname.Substring(0, pathname.Length - 1); builder.Append(pathname); } //判斷是否反斜線 if (Slashes) { builder.Append("/"); } Dictionary<string, string=""> searchList = GetSearchList(); if (searchList != null && searchList.Count > 0) { builder.Append("?"); bool isFirst = true; foreach (var item in searchList) { if (isFirst == false) { builder.Append("&"); } isFirst = false; builder.AppendFormat("{0}={1}", item.Key, EncodeValue ? HttpUtility.UrlEncode(item.Value) : item.Value); } } //錨點 builder.Append(Hash); return builder.ToString(); } #region 靜態方法 /// <summary> /// 擷取源字串中所有的連結(可能有重複) /// </summary> ///<param name="content">源字串 /// <returns></returns> public static List<string> GetUrlList(string content) { List<string> list = new List<string>(); Regex re = new Regex(@"(?<url>http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?)"); MatchCollection mc = re.Matches(content); foreach (Match m in mc) { if (m.Success) { string url = m.Result("${url}"); list.Add(url); } } return list; } /// <summary> /// 將字串中的連結成標籤 /// </summary> ///<param name="content"> /// <returns></returns> public static string ReplaceToA(string content) { Regex re = new Regex(@"(?<url>http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?)"); MatchCollection mc = re.Matches(content); foreach (Match m in mc) { content = content.Replace(m.Result("${url}"), String.Format("</url>{0}", m.Result("${url}"))); } return content; } #endregion}</url></string></string></string></string,></string></string></string></string,></string,></string,></string,>
所屬原始碼庫:https://github.com/tianma3798/Common
感謝閱讀,希望能協助到大家,謝謝大家對本站的支援!