C# 分析Url链接 获取对应参数值

拆分获取方法:

///
        /// 分析url链接,返回参数集合
        /// 
        /// url链接
        /// 
        /// 
        public static System.Collections.Specialized.NameValueCollection ParseUrl(string url, out string baseUrl)
        {
            baseUrl = "";
            if (string.IsNullOrEmpty(url))
                return null;
            System.Collections.Specialized.NameValueCollection nvc = new System.Collections.Specialized.NameValueCollection();

            try
            {
                int questionMarkIndex = url.IndexOf('?');

                if (questionMarkIndex == -1)
                    baseUrl = url;
                else
                    baseUrl = url.Substring(0, questionMarkIndex);
                if (questionMarkIndex == url.Length - 1)
                    return null;
                string ps = url.Substring(questionMarkIndex + 1);

                // 开始分析参数对   
                System.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex(@"(^|&)?(\w+)=([^&]+)(&|$)?", System.Text.RegularExpressions.RegexOptions.Compiled);
                System.Text.RegularExpressions.MatchCollection mc = re.Matches(ps);

                foreach (System.Text.RegularExpressions.Match m in mc)
                {
                    nvc.Add(m.Result("$2").ToLower(), m.Result("$3"));
                }

            }
            catch { }
            return nvc;
        }

调用:

  public static void Main(string[] args)
        {            

            var str =
                "https://aa.com/pages/shopdetail/shopdetail?EnclosureId=null&Title=云科技室内温度传感器&ProductId=1";
            var aa = ParseUrl(str, out str);

            Console.WriteLine("1:"+aa["EnclosureId"]);
            Console.WriteLine("2:" + aa["Title"]);
            Console.WriteLine("3:" + aa["ProductId"]);
        }

不要重复调用该方法获取一个Url里面的参数。 

 

你可能感兴趣的:(C#,日常代码)