I have a complex Regex which is used to help strip out HTML from user input. I’m aware that .NET caches static Regex calls to some extent, but this one is big and used frequently, so I’d like it to hang around.
In a web site project, I’d like to define it as a shared object, within a helper class in App_Code, eg:
AppHelper.vb in App_Code:
Public Class AppHelper
Private Shared _rxRemoveHTML As New Regex("(<[\s\S]*?(style|script)[\s\S]*?>[\s\S]*?</[\s\S]*?(style|script)[\s\S]*?>)|<[^<>]*>|&#[0-9a-z]+;|&#|<|>|\\|`|\t", RegexOptions.IgnoreCase + RegexOptions.Multiline)
This will keep it alive for the life of the app.
A public function does the work:
Public Shared Function RemoveHTML(ByVal sIn As String) As String
Return _rxRemoveHTML.Replace(sIn, "")
End Function
The question is, is this thread-safe and otherwise ok for a web app?
Yes, it is perfectly safe to do so. Taken from MSDN: