views:

95

answers:

2

i need to know if its safe to create a static Regex object like this

public static Regex s_Regex_ExtractEmails = new Regex(@"\b[A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4}\b");

and call it staticaly from asp.net threads like this

s_Regex_ExtractEmails.Matches("my email is [email protected]")

wont this cause any problems? i am doing this basically as an optimization so that the Regex object can be precompiled and reused thanks.

+8  A: 

Yes, Regex objects are thread-safe. From the docs:

The Regex class is immutable (read-only) and is inherently thread safe. Regex objects can be created on any thread and shared between threads.

You might want to consider using RegexOptions.Compiled too - although don't assume it'll help performance; measure!

Jon Skeet
A: 

Not only safe, it is recommnded to use like this when you can.This approach will improve the performance of your application.