2

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!

1
  • 1
    What markup did you expect it to generate? Commented Feb 15, 2010 at 22:56

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, but what if: string urlParameters = "this is a string width=100&height=200";
Well, that's a different question. The second method will still work, or you can extract the query string from your string (a naive regex is (\w+=\w+)+). You should edit your question or write a new one, explain exactly in what format your strings are.
0

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.

1 Comment

I am using regex because the String is not coming from the URL it is coming from another source and the URL is just part of the source.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.