开发者

regex.replace Querystring parameters

开发者 https://www.devze.com 2022-12-20 01:38 出处:网络
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

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:sol开发者_JAVA技巧id 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);


Is there a reason why you would want to use a regular expression to handle this instead of a Request.QueryString function to grab the data and put this into the string instead?

Right now you would have to make a much more specific Regular Expression to get the value of each key/value pairs and put them into the replace.

0

精彩评论

暂无评论...
验证码 换一张
取 消