firasdib / Regex101

This repository is currently only used for issue tracking for www.regex101.com
3.2k stars 198 forks source link

[GeneratedRegex] flavor in c# code generator #2203

Open kasperk81 opened 6 months ago

kasperk81 commented 6 months ago

.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

danmoseley commented 5 months ago

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

firasdib commented 5 months ago

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

kasperk81 commented 5 months ago

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