Regex101 icon indicating copy to clipboard operation
Regex101 copied to clipboard

[GeneratedRegex] flavor in c# code generator

Open kasperk81 opened this issue 1 year ago • 4 comments

.net 7 added [GeneratedRegex] attribute for compile-time code generation. https://learn.microsoft.com/en-us/dotnet/standard/base-types/regular-expression-source-generators

feature request: show [GeneratedRegex] syntax in regex101's codegenerator as an alternative

Code Generator Language

C#

Code Snippet

current syntax, works with all versions of .net:

image

new / alternative code-generator syntax with performance advantage, works with .net 7 and above:

using System;
using System.Text.RegularExpressions;

string input = @"start to finish";

Match m = Pattern.Get().Match(input);
Console.WriteLine("'{0}' found at index {1}", m.Value, m.Index);

internal partial class Pattern
{
    [GeneratedRegex(@"^.*$")]
    public static partial Regex Get();
}

https://godbolt.org/z/Ws7dE8enc

kasperk81 avatar Jan 02 '24 17:01 kasperk81

@firasdib this should be essentially just sugar, the regex goes in the [GeneratedRegex(...)] instead of into string pattern = "...".

danmoseley avatar Jan 26 '24 00:01 danmoseley

Is one method preferred over the other? I will trust your judgement :)

firasdib avatar Jan 27 '24 13:01 firasdib

yes with GeneratedRegex attribute compiler generates c# code for a given pattern at build time, then compiles it to .net assembly https://learn.microsoft.com/en-us/dotnet/standard/base-types/regular-expression-source-generators

kasperk81 avatar Jan 27 '24 13:01 kasperk81