Reputation: 7684
Given the following example "strings":
I want to remove the name/value pair for token in all cases, so I am left with:
Note: I cannot use the Uri class for various reason.
Is there a single regex or string function that can do this?
Upvotes: 3
Views: 2193
Reputation: 20852
(\btoken=[^&]*&|[\?&]token=[^&]*$)
This regexp removes the token
param in all variations, including the variation where token is the only param:
Explanation:
Part 1: \btoken=[^&]*&
...catches token
including its value and a terminating &
.
This part handles the following cases:
Part 2: [\?&]token=[^&]*$
...catches token
when it appears as the last parameter and/or the only parameter, together with its leading ?
or &
.
This part handles the following cases:
Upvotes: 3
Reputation: 100547
Consider using HttpUtility.ParseQueryString ( http://msdn.microsoft.com/en-us/library/ms150046.aspx ) to parse and UriBuilder to construct back...
Be careful with all encodings and ordering of parameters in query string - Uri class would helped with it.
Upvotes: 2
Reputation: 8994
I think this will do it for you (haven't had a chance to test).
string s = "somePage.aspx?id=20&name=brian&token=1234";
s = Regex.Replace(s, @"(&token=[^&\s]+|token=[^&\s]+&?)", "");
Edit: Updated to correctly handle the case where token is the first pair.
Upvotes: 5