Home
C#
static Regex
Updated Sep 12, 2023
Dot Net Perls
Static Regex. A static Regex helps performance. It can be used throughout methods in the C# program. This reduces allocations and can simplify programs.
Single-instance Regex. A static Regex is essentially a single-instance regular expression. Static regular expressions have clear performance advantages.
Regex.Match
To start, we demonstrate the use of a static Regex. You can use a static variable initializer at the class level to instantiate the regular expression with the new operator.
Then You can access the Regex by its identifier and call methods such as Match, Matches and IsMatch on it.
Regex.Matches
Next This program finds the first word starting with a capital R in the input string.
Tip The biggest benefit of static Regex instances is that they will not likely be created more than once.
Info Your regular expression can be shared between many different methods on the type. This will improve performance.
using System; using System.Text.RegularExpressions; class Program { static Regex _rWord = new Regex(@"R\w*"); static void Main() { // Use the input string. // ... Then try to match the first word starting with capital R. string value = "This is a simple /string/ for Regex."; Match match = _rWord.Match(value); Console.WriteLine(match.Value); } }
Regex
Performance. Static regular expressions show a performance advantage. Static fields do not have an instance expression, so resolving the location of their memory storage is slightly faster.
Performance, continued. Regular expressions are not an ideal solution for performance. They can be sped up with considerations of their allocation patterns, as with the static modifier.
static
A summary. We implemented a static regular expression. This can improve performance by enhancing the access patterns to the regular expression and restricting heap allocations.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Sep 12, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen