tags:

views:

33

answers:

2

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.

A: 

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
AllenG
That's quite interesting. As I said in my reply to JMarsch, I was hoping to put this stuff in a configuration file, and this seems like a possible way of doing things.Don't worry - I'll do things at my own risk ;)
Shane
+1  A: 
JMarsch
Thanks a lot for your prompt reply JMarsch! I had thought that this was the route I'd be going down. I'd just wondered if I could create a single regular expression to do the job, as I could then put it in a config file and make the replacement 'generic' in the C# component.Thanks for your help.
Shane