Match.Result(String) Method

Definition

Returns the expansion of the specified replacement pattern.

C#
public virtual string Result(string replacement);

Parameters

replacement
String

The replacement pattern to use.

Returns

The expanded version of the replacement parameter.

Exceptions

replacement is null.

Expansion is not allowed for this pattern.

Examples

The following example replaces the hyphens that begin and end a parenthetical expression with parentheses.

C#
using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern = "--(.+?)--";
      string replacement = "($1)";
      string input = "He said--decisively--that the time--whatever time it was--had come.";
      foreach (Match match in Regex.Matches(input, pattern))
      {
         string result = match.Result(replacement);
         Console.WriteLine(result);
      }
   }
}
// The example displays the following output:
//       (decisively)
//       (whatever time it was)

The regular expression pattern --(.+?)-- is interpreted as shown in the following table.

Pattern Description
-- Match two hyphens.
(.+?) Match any character one or more times, but as few times as possible. This is the first capturing group.
-- Match two hyphens.

Note that the regular expression pattern --(.+?)-- uses the lazy quantifier +?. If the greedy quantifier + were used instead, the regular expression engine would find only a single match in the input string.

The replacement string ($1) replaces the match with the first captured group, which is enclosed in parentheses.

Remarks

Whereas the Regex.Replace method replaces all matches in an input string with a specified replacement pattern, the Result method replaces a single match with a specified replacement pattern. Because it operates on an individual match, it is also possible to perform processing on the matched string before you call the Result method.

The replacement parameter is a standard regular expression replacement pattern. It can consist of literal characters and regular expression substitutions. For more information, see Substitutions.

Applies to

Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

See also