ASP.NET 正则替换URL参数值

public class HomeController : Controller
    {
        public ActionResult Index()
        {
            var url = "http://www.ly.com?ak=abcdefg&user=sbd";
            var queryString = "ak=hello&user=test&passpord=111";

            url = this.DealQueryString(url, queryString);

            return Content(url);
        }

        private string DealQueryString(string url, string queryString)
        {
            var arr = queryString.Split('&');
            foreach (var item in arr)
            {
                var arrSub = item.Split('=');
                url = this.DealQueryString(url, arrSub[0], arrSub[1]);
            }
            return url;
        }

        private string DealQueryString(string url, string key, string val)
        {
            var exp = key + "=([^&]*)";
            var r = new Regex(exp);
            if (r.IsMatch(url))
            {
                url = r.Replace(url, key + "=" + val);
            }
            else
            {
                url += url.Contains("?") ? "&" : "?";
                url += key + "=" + val;
            }
            //url = Regex.Replace(url, exp, para + "=" + val);

            return url;
        }
    }

 

posted @ 2016-07-02 18:30  屌丝大叔的笔记  阅读(1716)  评论(0编辑  收藏  举报