Regex - match part of a URL querystring

I struggle mightily with Regex, so every time that I achieve something I blog it.

Today, I wanted to look into the URL of a web site and remove part of the query string. Specifically, in these cases:

www.mysite.com?userid=123xy

www.mysite.com?userid=123xy&username=joe

www.mysite.com?tag=xyz&userid=1ww45

www.mysite.com?tag=xyz&userid=1g3x5&username=joe

I wanted to remove the 'userid=xxxxx' out of the url.

Related Articles

... and you 'll find more on the NET Development Menu

 

Dim r As New Regex("[&?]userID=[^\s&#]+", RegexOptions.IgnoreCase)
Dim strUrl As String = r.Replace(app.Context.Request.Url.ToString, "")
strUrl = strUrl.Replace("aspx&", "aspx?")
Response.Redirect(strUrl)

For my notes:

[&?] Match one of the items in the list

userID= Match the literal string

[^\s&#]+ the caret(^) inside the brackets ([]) means to match anything NOT in the list

\s is a space

Match a single character NOT present in the list below «[^\s&#]+»
   Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
   A whitespace character (spaces, tabs, and line breaks) «\s»
   One of the characters “&#” «&#»

Created with RegexBuddy


RealWorldCode gives developers practical, real‑world solutions with clean, working code — no fluff, no theory, just answers.
Links
Home
Knowledge Areas
Sitemap
Contact
Et cetera
Privacy Policy
Terms and Conditions
Cookie Preferences