首页 > Web开发 > 详细

正则表达式解析url参数

时间:2016-05-19 14:52:02      阅读:418      评论:0      收藏:0      [点我收藏+]

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

正好项目中要用到 捣鼓了好久还是不会.最终放弃使用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;
            }
            var m = Regex.Matches(path, @"(?<=\?|&)[\w\={},:‘‘""]*(?<=[^#])", 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;
        }

 

正则表达式解析url参数

原文:http://www.cnblogs.com/LQBlog/p/5508529.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!