Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -295,9 +295,9 @@ static RegexOptions GetRegexOptionsFromArgument(ImmutableArray<IArgumentOperatio
return SyntaxFactory.ParseExpression(optionsLiteral);

case UpgradeToGeneratedRegexAnalyzer.PatternArgumentName:
if (argument.Value.ConstantValue.Value is string str && str.Contains('\\'))
if (argument.Value.ConstantValue.Value is string str && ShouldUseVerbatimString(str))
{
// Special handling for string patterns with escaped characters
// Special handling for string patterns with escaped characters or newlines
string escapedVerbatimText = str.Replace("\"", "\"\"");
return SyntaxFactory.ParseExpression($"@\"{escapedVerbatimText}\"");
}
Expand All @@ -313,6 +313,13 @@ static RegexOptions GetRegexOptionsFromArgument(ImmutableArray<IArgumentOperatio
}
}

static bool ShouldUseVerbatimString(string str)
{
// Use verbatim string syntax if the string contains backslashes or newlines
// to preserve readability, especially for patterns with RegexOptions.IgnorePatternWhitespace
return str.IndexOfAny(['\\', '\n', '\r']) >= 0;
}

static string Literal(string stringifiedRegexOptions)
{
if (int.TryParse(stringifiedRegexOptions, NumberStyles.Integer, CultureInfo.InvariantCulture, out int options))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1336,6 +1336,70 @@ static void Main(string[] args)
await VerifyCS.VerifyCodeFixAsync(test, expectedFixedCode);
}

[Fact]
public async Task MultilineVerbatimStringPreservedByFixer()
{
string test = """
using System.Text.RegularExpressions;

static class Class
{
private static Regex r = [|new Regex(@"a
b
c", RegexOptions.IgnorePatternWhitespace)|];
}
""";

string expectedFixedCode = """
using System.Text.RegularExpressions;

static partial class Class
{
private static Regex r = MyRegex();

[GeneratedRegex(@"a
b
c", RegexOptions.IgnorePatternWhitespace)]
private static partial Regex MyRegex();
}
""";

await VerifyCS.VerifyCodeFixAsync(test, expectedFixedCode);
}

[Fact]
public async Task MultilineStringConcatenationPreservedByFixer()
{
string test = """
using System.Text.RegularExpressions;

static class Class
{
private const string foo = "bar";
private static Regex r1 = [|new Regex(@"a " + foo + @"
b
c", RegexOptions.IgnorePatternWhitespace)|];
}
""";

string expectedFixedCode = """
using System.Text.RegularExpressions;

static partial class Class
{
private const string foo = "bar";
private static Regex r1 = MyRegex();

[GeneratedRegex(@"a bar
b
c", RegexOptions.IgnorePatternWhitespace)]
private static partial Regex MyRegex();
}
""";

await VerifyCS.VerifyCodeFixAsync(test, expectedFixedCode);
}

[Fact]
public async Task TestAsArgument()
{
Expand Down
Loading