From cbd5ef9ca8a577613d32f5971ee7b94f43676ce6 Mon Sep 17 00:00:00 2001 From: William Forney Date: Wed, 16 Sep 2026 09:09:26 -0700 Subject: [PATCH] Cache GUID validation regex Avoid compiling the GUID validation regex on every call and use the source-generated regex on modern target frameworks.\n\nCo-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- SharedCode.Core/Text/StringExtensions.cs | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/SharedCode.Core/Text/StringExtensions.cs b/SharedCode.Core/Text/StringExtensions.cs index cb7c044..9a58cdf 100644 --- a/SharedCode.Core/Text/StringExtensions.cs +++ b/SharedCode.Core/Text/StringExtensions.cs @@ -12,6 +12,12 @@ namespace SharedCode.Text; /// public static partial class StringExtensions { + private const string GuidPattern = + "^[A-Fa-f0-9]{32}$|" + + "^({|\\()?[A-Fa-f0-9]{8}-([A-Fa-f0-9]{4}-){3}[A-Fa-f0-9]{12}(}|\\))?$|" + + "^({)?[0xA-Fa-f0-9]{3,10}(, {0,1}[0xA-Fa-f0-9]{3,6}){2}, {0,1}({)" + + "([0xA-Fa-f0-9]{3,4}, {0,1}){7}[0xA-Fa-f0-9]{3,4}(}})$"; + /// /// Default masking character used in a mask. /// @@ -419,12 +425,11 @@ public static bool IsGuid(this string @this) { _ = @this ?? throw new ArgumentNullException(nameof(@this)); - var format = new Regex( - "^[A-Fa-f0-9]{32}$|" + "^({|\\()?[A-Fa-f0-9]{8}-([A-Fa-f0-9]{4}-){3}[A-Fa-f0-9]{12}(}|\\))?$|" - + "^({)?[0xA-Fa-f0-9]{3,10}(, {0,1}[0xA-Fa-f0-9]{3,6}){2}, {0,1}({)([0xA-Fa-f0-9]{3,4}, {0,1}){7}[0xA-Fa-f0-9]{3,4}(}})$"); - var match = format.Match(@this); - - return match.Success; +#if NET8_0_OR_GREATER + return GuidRegex().IsMatch(@this); +#else + return GuidRegex.IsMatch(@this); +#endif } /// @@ -950,5 +955,10 @@ private static void CreateAlphaNumMask(StringBuilder buffer, string source, char #if NET8_0_OR_GREATER [GeneratedRegex("")] private static partial Regex HtmlTagRegex(); + + [GeneratedRegex(GuidPattern)] + private static partial Regex GuidRegex(); +#else + private static readonly Regex GuidRegex = new(GuidPattern, RegexOptions.Compiled); #endif }