title: Regex to remove onclick="" attributes from HTML elements in ASP.NET C# (Server-side)
body: <p>I'm trying to write a regex function to remove onclick (also onload, onmouseover etc.) attributes from HTML elements. I want to do this on the server side before the HTML is sent to the client.</p>
  
  <p>I have content coming from a Rich Text editor and being displayed on screen in a div, and I want to protect against XSS (Cross Site Scripting). Obviously I can't HTML encode it using Server.HtmlEncode() because the rich text stores the text as HTML markup, so I'm using a blacklisting approach, looking for certain elements such as <code>&lt;script&gt;</code> and <code>&lt;style&gt;</code>. I'm now trying to look for onclick, onmouseover etc. attributes, so far I have the following:</p>
  
  <pre><code>returnVal = Regex.Replace(returnVal, @"\&lt;(.*?)(\ on[a-z]+\=\""?.*?\""?)*(.*?)\&gt;",
                 "&lt;$1 $3&gt;", RegexOptions.Singleline | RegexOptions.IgnoreCase);
  </code></pre>
  
  <p>...which isn't working, and I've tried a few variations. Basically I want it so that...</p>
  
  <pre><code>&lt;p style="font-style: italic" onclick="alert('hacked!!');"&gt;Hello World&lt;/p&gt;
  </code></pre>
  
  <p>gets turned into...</p>
  
  <pre><code>&lt;p style="font-style: italic"&gt;Hello World&lt;/p&gt;
  </code></pre>
  
  <p>Any ideas? Cheers!</p>