本文介绍了regex.replace 查询字符串参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道这是否可能,我有以下正则表达式 (?<=[\?|\&])(?[^\?=\&#]+)=?(?[^\?=\&#]*)&它将 URL 拆分为键/值对.我想在替换函数中使用它来构建一些标记:

string sTest = "test.aspx?width=100&height=200&";ltTest.Text = Regex.Replace(sTest, @"(?<=[\?|\&])(?<key>[^\?=\&\#]+)=?(?<值>[^\?=\&\#]*)&","< div style='width:$2px; height:$2px; border:solid 1px red;'>asdf</div>");

这是生成:

test.aspx?

有什么想法吗?

提前致谢!

解决方案

首先,.net 有更好的方法来处理您的问题.考虑 HttpUtility.ParseQueryString::>

string urlParameters = "width=100&height=200";NameValueCollection 参数 = HttpUtility.ParseQueryString(urlParameters);s = String.Format("<div style='width:{0}px; height:{1}px;'>asdf</div>",参数["宽度"], 参数["高度"]);

这会照顾到你的逃跑,所以这是一个更好的选择.

接下来,对于这个问题,您的代码失败是因为您使用错误.您正在寻找成对的 key=value,并<div width={value} height={value}> 替换每一对代码>.所以你最终会得到许多 DIV 作为值.
例如,您应该进行更手术式的匹配(添加一些检查):

string width = Regex.Match(s, @"width=(\d+)").Groups[1].Value;string height = Regex.Match(s, @"height=(\d+)").Groups[1].Value;s = String.Format("<div style='width:{0}px; height:{1}px;'>asdf</div>",宽度,高度);

I don't know if this is even possible, I have the following regular expression (?<=[\?|\&])(?[^\?=\&#]+)=?(?[^\?=\&#]*)& which splits a URL into key/value pairs. I would like to use this in a replace function to build some markup:

string sTest = "test.aspx?width=100&height=200&";
            ltTest.Text = Regex.Replace(sTest, @"(?<=[\?|\&])(?<key>[^\?=\&\#]+)=?(?<value>[^\?=\&\#]*)&",
                                                "< div style='width:$2px; height:$2px; border:solid 1px red;'>asdf</div>");

this is generating:

test.aspx?<div style='width:100px; height:100px; border:solid 1px red;'>asdf</div><div style='width:200px; height:200px; border:solid 1px red;'>asdf</div>

Any ideas?

Thanks in advance!

解决方案

First, .net has better ways of dealing with your peoblem. Consider HttpUtility.ParseQueryString:

string urlParameters = "width=100&height=200";
NameValueCollection parameters = HttpUtility.ParseQueryString(urlParameters);
s = String.Format("<div style='width:{0}px; height:{1}px;'>asdf</div>",
                   parameters["width"], parameters["height"]);

That takes care of escaping for you, so it is a better option.


Next, to the question, your code fails because you're using it wrong. you're looking for pairs of key=value, and replacing every pair with <div width={value} height={value}>. So you end up with ad many DIVs as values.
You should make a more surgical match, for example (with some added checks):

string width = Regex.Match(s, @"width=(\d+)").Groups[1].Value;
string height = Regex.Match(s, @"height=(\d+)").Groups[1].Value;
s = String.Format("<div style='width:{0}px; height:{1}px;'>asdf</div>",
                   width, height);

这篇关于regex.replace 查询字符串参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 11:43