Shane
Shane

Reputation: 1

rewriting URLs with regular expressions

I wish to transform a querystring using a regular expression replace in C#.

I have a number of defined querystring parameters (i.e. A, B and C).

I wish to transform something like this

page.aspx?A=XXX&B=YYY&C=1

into:

page/XXX/YYYY/true

Note that the first two parameters values for A and B are simply concatenated, but the part I'm having trouble with is changing the C=1 to true in the output.

Can this even be done? If the C=1 part isn't found, I don't want to output anything:

page.aspx?A=XXX&B=YYY

becomes:

page/XXX/YYY

I don't think the order of A and B in the source querystring are ever in a different order, but could something be written to cope if B came before A?

I've been trying all sorts. Crucially, I'd love to know if this can be done, because if not, I'll have to do it another way.

Upvotes: 0

Views: 172

Answers (2)

JMarsch
JMarsch

Reputation: 21753

You might be better off not using a regular expression.
Try this:


            string urlString = "page.aspx?A=XXX&B=YYY&C=1";
            var builder = new System.UriBuilder(urlString);
            // the first character in Query will be a "?"
            string[] queries = builder.Query.Substring(1).Split('&');

At this point, you have each query item separated into its own string. You can use the built-in string methods on each element of the array (like queryies[0].StartsWith()) to identify which string is the "C" query string, and build your path as you need.

Upvotes: 1

AllenG
AllenG

Reputation: 8190

As Robert H mentions in the comments, you may get better mileage out of String.Replace() than you do with Regex. What I would do, though, with regex (if you really need it) is split them into three different statements so that you're calling
Regex.Replace(yourString, [patern for A=], "page/");
Regex.Replace(yourString, [patern for B=], "/");
Regex.Replace(yourString, [patern for C=], "true");

If you want to be really clear on what you're doing, call Regex.Match() for each pattern first to verify the pattern exists in your input. Then, if it's missing, you can just skip that replace.

Thus, this should work for you: Note: no error checking done, use "as-is" at own risk

string input = "A=xxx&B=yyy&C=1";
string input2 = "A=xxx&B=yyy";

if(Regex.Match(input, "A=").Success) input = Regex.Replace(input, "A=", "page/");
if(Regex.Match(input,@"\&B=").Success) input = Regex.Replace(input, @"\&B=", "/");
if(Regex.Match(input,@"\&C=1").Success) input = Regex.Replace(input, @"\&C=1", "/true");

if(Regex.Match(input2, "A=").Success) input2 = Regex.Replace(input2, "A=", "page/");
if(Regex.Match(input2,@"\&B=").Success) input2 = Regex.Replace(input2, @"\&B=", "/");
if(Regex.Match(input2,@"\&C=1").Success) input2 = Regex.Replace(input2, @"\&C=1", "/true");

Console.WriteLine(input); //Output = page/xxx/yyy/true
Console.WriteLine(input2); //Output = page/xxx/yyy

Upvotes: 0

Related Questions