Fix NRE when MatchEvaluator returns null (dotnet/corefx#39779)
authorDan Moseley <danmose@microsoft.com>
Fri, 26 Jul 2019 05:27:18 +0000 (22:27 -0700)
committermsftbot[bot] <48340428+msftbot[bot]@users.noreply.github.com>
Fri, 26 Jul 2019 05:27:18 +0000 (05:27 +0000)
* Fix NRE when MatchEvaluator returns null

* Update Regex.Replace.Tests.cs

* Use fancy syntax

Commit migrated from https://github.com/dotnet/corefx/commit/98227597b152076cb02c55bb695c572c14284e32

src/libraries/System.Text.RegularExpressions/src/System/Text/RegularExpressions/Regex.Replace.cs
src/libraries/System.Text.RegularExpressions/tests/Regex.Replace.Tests.cs

index 22e5f3f..cb78992 100644 (file)
@@ -186,7 +186,7 @@ namespace System.Text.RegularExpressions
                             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;
index 0cbf545..5bcfa77 100644 (file)
@@ -224,6 +224,25 @@ namespace System.Text.RegularExpressions.Tests
             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()
         {