Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p><strike></p> <p>Just going off the top of my head...</p> <pre><code>string url = "somepage.aspx?cat=22&amp;id=SomeId&amp;param2=4"; Regex regex = new Regex("([\?\&amp;])id=[^\?\&amp;]+"); url = regex.replace(url, "\1"); System.Diagnostics.Debug.WriteLine("url = " + url); </code></pre> <p></strike></p> <p><strong>Update 2010-03-05 11:12 PM PST</strong></p> <p>I've been shamed by a comment into actually testing my code. What are you, my QA department? Here's a working example using MSTest.</p> <pre><code> Regex regex = new Regex(@"([\?\&amp;])id=[^\&amp;]+[\&amp;]?"); [TestMethod] public void RegexReplacesParameterInMiddle() { string url = "somepage.aspx?cat=22&amp;id=SomeId&amp;param2=4"; url = regex.Replace(url, "$1"); Assert.AreEqual("somepage.aspx?cat=22&amp;param2=4",url); } [TestMethod] public void RegexReplacesParameterInFront() { string url = "somepage.aspx?id=SomeId&amp;cat=22&amp;param2=4"; url = regex.Replace(url, "$1"); Assert.AreEqual("somepage.aspx?cat=22&amp;param2=4", url); } [TestMethod] public void RegexReplacesParameterAtEnd() { string url = "somepage.aspx?cat=22&amp;param2=4&amp;id=SomeId"; url = regex.Replace(url, "$1"); Assert.AreEqual("somepage.aspx?cat=22&amp;param2=4&amp;", url); } [TestMethod] public void RegexReplacesSoleParameter() { string url = "somepage.aspx?id=SomeId"; url = regex.Replace(url, "$1"); Assert.AreEqual("somepage.aspx?", url); } public void RegexIgnoresMissingParameter() { string url = "somepage.aspx?foo=bar&amp;blet=monkey"; url = regex.Replace(url, "$1"); Assert.AreEqual("somepage.aspx?foo=bar&amp;blet=monkey", url); } </code></pre> <p>The regex, interpreted, says:</p> <pre><code>Look for a "?" or an "&amp;" character (and store it as a backreference) followed by "id=" followed by one or more non-"&amp;" characters. optionally followed by another "&amp;" </code></pre> <p>Then replace that expression with the backreference, so you don't lose your initial ?/&amp;.</p> <p><strong>note</strong> -- as you can see from the tests, this emits a trailing ? or &amp; when the replaced parameter is the only one or the last one, respectively. You could use string methods to get rid of that, though if somebody knows how to keep them out of the result using only regular expressions it would be excellent to see. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload