Regex101 icon indicating copy to clipboard operation
Regex101 copied to clipboard

.NET Code generator update from @" to """ for pattern

Open working-name opened this issue 1 year ago • 1 comments

franckleveque: It seems that since C# 11 (.net 7) a new way is using """ at the beginning and the end of a string to allow brut string without any escaping sequence interpretation but it is not preceded by @. However I never used it. https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/strings/

Incidental find while discussing another aspect of .NET behavior.

This regex does not produce working code:

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"""

""\w+""

""";
        string input = @"this is a 

""test""

";
        RegexOptions options = RegexOptions.Multiline;
        
        foreach (Match m in Regex.Matches(input, pattern, options))
        {
            Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
        }
    }
}

We should utilize """ raw string literals instead, which would make the code above output as expected:

        string pattern = """

"\w+"

""";

NOTE: the code generator will likely have to count the number of consecutive " characters inside the user's regex pattern, and simply enclose the whole shabang in +1 " characters, i.e.

string input = """""I like apples, """", and oranges.""""";

working-name avatar Jun 08 '24 22:06 working-name

A very good suggestion, preferably with indentation as well:

    string pattern = """

        "\w+"

        """;

doterik avatar May 08 '25 18:05 doterik