Brian David Berman
Brian David Berman

Reputation: 7684

String function (regex?) to remove query string pair from url string

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

Answers (3)

Jpsy
Jpsy

Reputation: 20852

(\btoken=[^&]*&|[\?&]token=[^&]*$)

See https://regexr.com/3ia6k

This regexp removes the token param in all variations, including the variation where token is the only param:

  • somePage.aspx?token=1234

Explanation:

Part 1: \btoken=[^&]*&

...catches token including its value and a terminating &.
This part handles the following cases:

  • somePage.aspx?id=20&token=1234&name=brian
  • somePage.aspx?token=1234&id=20&name=brian

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:

  • somePage.aspx?id=20&name=brian&token=1234
  • somePage.aspx?token=1234

Upvotes: 3

Alexei Levenkov
Alexei Levenkov

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

ean5533
ean5533

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

Related Questions