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?
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.
(\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:
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With