Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Given the following example "strings":

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

I want to remove the name/value pair for token in all cases, so I am left with:

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

Note: I cannot use the Uri class for various reason.

Is there a single regex or string function that can do this?

like image 735
Brian David Berman Avatar asked Mar 19 '26 03:03

Brian David Berman


2 Answers

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.

like image 161
ean5533 Avatar answered Mar 21 '26 18:03

ean5533


(\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
like image 35
Jpsy Avatar answered Mar 21 '26 18:03

Jpsy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!