Skip to content

Commit 8b80947

Browse files
Fix verbatim escaping in regex code generator (#115447)
1 parent 2c94e69 commit 8b80947

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

src/libraries/System.Text.RegularExpressions/gen/UpgradeToGeneratedRegexCodeFixer.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -298,7 +298,8 @@ static RegexOptions GetRegexOptionsFromArgument(ImmutableArray<IArgumentOperatio
298298
}
299299
else if (argument.Value.ConstantValue.Value is string str && str.Contains('\\'))
300300
{
301-
return SyntaxFactory.ParseExpression($"@\"{str}\"");
301+
string escapedVerbatimText = str.Replace("\"", "\"\"");
302+
return SyntaxFactory.ParseExpression($"@\"{escapedVerbatimText}\"");
302303
}
303304
else
304305
{

src/libraries/System.Text.RegularExpressions/tests/FunctionalTests/UpgradeToGeneratedRegexAnalyzerTests.cs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -905,6 +905,48 @@ public static string CollapseWhitespace(this string text) =>
905905
await VerifyCS.VerifyCodeFixAsync(test, expectedFixedCode);
906906
}
907907

908+
[Fact]
909+
public async Task CodeFixForConstantPatternExpressionWithQuote()
910+
{
911+
// From https://github.com/dotnet/runtime/issues/104371
912+
// When constant expression patterns need to be escaped, we generate
913+
// a verbatim string literal. However, we still need to escape quotes.
914+
string expression = """
915+
"[" + @"\/:<>|" + "\"]"
916+
""";
917+
918+
string test = $@"using System.Text;
919+
using System.Text.RegularExpressions;
920+
921+
public class Program
922+
{{
923+
public static void Main(string[] args)
924+
{{
925+
var isMatch = [|Regex.IsMatch("""", {expression})|];
926+
}}
927+
}}";
928+
929+
string verbatimPattern = """
930+
@"[\/:<>|""]"
931+
""";
932+
933+
string fixedSource = @$"using System.Text;
934+
using System.Text.RegularExpressions;
935+
936+
public partial class Program
937+
{{
938+
public static void Main(string[] args)
939+
{{
940+
var isMatch = MyRegex().IsMatch("""");
941+
}}
942+
943+
[GeneratedRegex({verbatimPattern})]
944+
private static partial Regex MyRegex();
945+
}}";
946+
947+
await VerifyCS.VerifyCodeFixAsync(test, fixedSource);
948+
}
949+
908950
[Fact]
909951
public async Task RawStringLiteralSyntaxPreservedByFixer()
910952
{

0 commit comments

Comments
 (0)