正则表达式解析url参数

解析url参数正则:(?<=\?|&)[\w\={}\\\\,-:'\s'""]*(?=[^#\s]|)

意思是(?<=\?|&) 从?或&符号开始匹配之后的满足 [\w\={}\\\\,-:'\s'""]*的字符串 但是不包含& 1个到多个   (?=[^#\s]|)匹配空格|#号之前或者空格之前结束

正好项目中要用到 捣鼓了好久还是不会.最终放弃使用split分割的方式解析发现好落伍

  public static NameValueCollection QueryString(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                return null;
            }
          var arr=path.Split(new char[] { '?' }, StringSplitOptions.RemoveEmptyEntries);
          if (arr.Length != 2)
          {
              return null;
          }
          var values = arr[1];
          arr = values.Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries);
          if (arr == null) return null;
          string[] itemvalues;
          NameValueCollection nvcs = new NameValueCollection();
          foreach (var item in arr)
          {
              itemvalues = item.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
              if (itemvalues == null || itemvalues.Length == 0) continue;
              nvcs.Add(itemvalues[0], itemvalues.Length <= 1 ? string.Empty : itemvalues[1]);
          }
          return nvcs;
        }

 

然后去看正则的文档 修改后版本

      public static NameValueCollection QueryString(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                return null;
            }
            path = System.Web.HttpUtility.UrlDecode(path);
            var m = Regex.Matches(path, @"(?<=\?|&)[\w\={}\\\\,-:'\s'""]*(?=[^#\s]|)", RegexOptions.None);        
            if (m.Count <= 0)
            {
                return null;
            }
            NameValueCollection nvcs = new NameValueCollection();
            string[] itemvalues = null;
            for (int i = 0; i < m.Count; i++)
            {
                itemvalues = m[i].Value.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
                if (itemvalues == null || itemvalues.Length == 0) continue;
                nvcs.Add(itemvalues[0], itemvalues.Length <= 1 ? string.Empty : itemvalues[1]);
            }
            return nvcs;
        }

其实微软有封装好的方法 System.Web.HttpUtility.ParseQueryString  传入?号后面一部分就好了  有种有现成的不用 造轮子的感觉。 但是无所谓啦 当练习正则 还有自己的代码也好把控一点

推荐一篇不错的讲正则的文章http://www.oschina.net/question/12_9507

 

posted @ 2016-05-19 14:18  意犹未尽  阅读(2463)  评论(0编辑  收藏  举报