firasdib / Regex101

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

Missing " in C# code generator #2104

Closed NCC1701M closed 11 months ago

NCC1701M commented 11 months ago

Bug Description

The code generator for C# removes " in the substitution string.

Reproduction steps

Lets say I have a file, containing text like this:

version: 3
version: 4
version: "5"

and I want to change the version representation to a uniform representation like

version: "3"
version: "4"
version: "5"

So I write this regex:

^version:\s*(?<version>\d+(?:\.\d+)*)$

and the following substitution:

version: "${version}"

When I test this in the Regex101 environment I get the expected results. But when I export it to C# code using the code generator, I get this code:

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"^version:\s*(?<version>\d+(?:\.\d+)*)$";
        string substitution = @"version: ${version}";
        string input = @"version: 3
version: 4
version: 5";
        RegexOptions options = RegexOptions.Multiline;

        Regex regex = new Regex(pattern, options);
        string result = regex.Replace(input, substitution);
    }
}

As you can see in the line where the variable substitution is declared, the string does not contain ", which causes the regex substitution to be incorrect.

Expected Outcome

The substitution variable should either be string substitution = @"version: ""${version}"""; or string substitution = "version: \"${version}\"";.

Complete code

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"^version:\s*(?<version>\d+(?:\.\d+)*)$";
        string substitution = @"version: ""${version}""";
        string input = @"version: 3
version: 4
version: 5";
        RegexOptions options = RegexOptions.Multiline;

        Regex regex = new Regex(pattern, options);
        string result = regex.Replace(input, substitution);
    }
}

Browser

Browser Version
Firefox: 114.0.2
Chrome 114.0.5735.199
Edge 114.0.1823.67

OS

Windows 11 22H2

firasdib commented 11 months ago

Thank you for the detailed report. Oversight on my part, adjusted locally, and will be pushed soon.