Match.Result(String) 方法

定義

傳回所指定取代模式的展開 (Expansion)。

public:
 virtual System::String ^ Result(System::String ^ replacement);
public virtual string Result (string replacement);
abstract member Result : string -> string
override this.Result : string -> string
Public Overridable Function Result (replacement As String) As String

參數

replacement
String

要使用的取代模式。

傳回

String

replacement 參數的展開版本。

例外狀況

replacementnull

這種模式不允許展開。

範例

下列範例會以括弧取代開頭和結尾括號運算式的連字號。

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)
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim pattern As String = "--(.+?)--"
      Dim replacement As String = "($1)"
      Dim input As String = "He said--decisively--that the time--whatever time it was--had come."
      For Each match As Match In Regex.Matches(input, pattern)
         Dim result As String = match.Result(replacement)
         Console.WriteLine(result)
      Next
   End Sub
End Module
' The example displays the following output:
'       (decisively)
'       (whatever time it was)

規則運算式模式 --(.+?)-- 的解譯方式如下表所示。

模式 描述
-- 比對兩個連字號。
(.+?) 比對任何一或多個字元,但盡可能少一次。 這是第一個擷取群組。
-- 比對兩個連字號。

請注意,正則運算式模式 --(.+?)-- 使用延遲數量詞 +? 。 如果改用了窮盡數量詞 + ,則正則運算式引擎只會在輸入字串中找到單一相符專案。

取代字串 ($1) 會將比對取代為第一個擷取的群組,以括弧括住。

備註

方法 Regex.Replace 會以指定的取代模式取代輸入字串中的所有相符專案,而 方法會 Result 以指定的取代模式取代單一比對。 因為它會在個別比對上運作,因此您也可以在呼叫 Result 方法之前,先對相符字串執行處理。

參數 replacement 是標準正則運算式取代模式。 它可以由常值字元和正則運算式替代所組成。 如需詳細資訊,請參閱替代

適用於

另請參閱