Skip to content

Commit

Permalink
Fix NRE when MatchEvaluator returns null (dotnet#39779)
Browse files Browse the repository at this point in the history
* Fix NRE when MatchEvaluator returns null

* Update Regex.Replace.Tests.cs

* Use fancy syntax
  • Loading branch information
danmoseley authored and msftbot[bot] committed Jul 26, 2019
1 parent 58a4d24 commit 9822759
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ private static string Replace(MatchEvaluator evaluator, Regex regex, string inpu
vsb.Append(input.AsSpan(prevat, match.Index - prevat));

prevat = match.Index + match.Length;
vsb.Append(evaluator(match));
vsb.Append(evaluator(match) ?? "");

if (--count == 0)
break;
Expand Down
19 changes: 19 additions & 0 deletions src/System.Text.RegularExpressions/tests/Regex.Replace.Tests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,25 @@ public void Replace_NoMatch()
Assert.Same(input, Regex.Replace(input, "no-match", new MatchEvaluator(MatchEvaluator1)));
}

[Theory]
[InlineData(RegexOptions.None)]
[InlineData(RegexOptions.RightToLeft)]
public void Replace_MatchEvaluatorReturnsNullOrEmpty(RegexOptions options)
{
string result = Regex.Replace("abcde", @"[abcd]", (Match match) => {
return match.Value switch
{
"a" => "x",
"b" => null,
"c" => "",
"d" => "y",
_ => throw new InvalidOperationException()
};
}, options);

Assert.Equal("xye", result);
}

[Fact]
public void Replace_Invalid()
{
Expand Down

0 comments on commit 9822759

Please sign in to comment.