Regex.Replace 方法

定義

在指定的輸入字串中,使用指定的取代字串來取代符合規則運算式模式的字串。

多載

Replace(String, MatchEvaluator, Int32, Int32)

在指定的輸入子字串中,使用 MatchEvaluator 委派所傳回的字串來取代符合規則運算式模式的指定最大字串數目。

Replace(String, String, String)

在指定的輸入字串中,使用指定的取代字串來取代符合指定之規則運算式的所有字串。

Replace(String, String, MatchEvaluator, RegexOptions, TimeSpan)

在指定的輸入字串中,使用 MatchEvaluator 委派所傳回的字串,取代所有與指定之規則運算式相符的子字串。 如果沒有找到相符項目,其他參數會指定修改比對作業的選項和逾時間隔。

Replace(String, String, MatchEvaluator, RegexOptions)

在指定的輸入字串中,使用由 MatchEvaluator 委派所傳回的字串,取代所有與指定之規則運算式相符的字串。 指定的選項會修改符合的作業。

Replace(String, String, String, RegexOptions, TimeSpan)

在指定的輸入字串中,使用指定的取代字串來取代符合指定之規則運算式的所有字串。 如果沒有找到相符項目,其他參數會指定修改比對作業的選項和逾時間隔。

Replace(String, String, String, RegexOptions)

在指定的輸入字串中,使用指定的取代字串來取代符合指定之規則運算式的所有字串。 指定的選項會修改符合的作業。

Replace(String, MatchEvaluator)

在指定的輸入字串中,使用由 MatchEvaluator 委派所傳回的字串,取代所有與指定之規則運算式相符的字串。

Replace(String, MatchEvaluator, Int32)

在指定的輸入字串中,使用 MatchEvaluator 委派所傳回的字串來取代符合規則運算式模式的指定最大字串數目。

Replace(String, String, MatchEvaluator)

在指定的輸入字串中,使用由 MatchEvaluator 委派所傳回的字串,取代所有與指定之規則運算式相符的字串。

Replace(String, String, Int32)

在指定的輸入字串中,使用指定的取代字串來取代符合規則運算式模式的指定最大字串數目。

Replace(String, String)

在指定的輸入字串中,使用指定的取代字串來取代符合規則運算式模式的所有字串。

Replace(String, String, Int32, Int32)

在指定的輸入子字串中,使用指定的取代字串來取代符合規則運算式模式的指定最大字串數目。

Replace(String, MatchEvaluator, Int32, Int32)

在指定的輸入子字串中,使用 MatchEvaluator 委派所傳回的字串來取代符合規則運算式模式的指定最大字串數目。

public:
 System::String ^ Replace(System::String ^ input, System::Text::RegularExpressions::MatchEvaluator ^ evaluator, int count, int startat);
public string Replace (string input, System.Text.RegularExpressions.MatchEvaluator evaluator, int count, int startat);
member this.Replace : string * System.Text.RegularExpressions.MatchEvaluator * int * int -> string
Public Function Replace (input As String, evaluator As MatchEvaluator, count As Integer, startat As Integer) As String

參數

input
String

用來搜尋比對的字串。

evaluator
MatchEvaluator

檢查每個符合項目並傳回原始符合字串或取代字串的自訂方法。

count
Int32

取代將發生的最多次數。

startat
Int32

在輸入字串中開始搜尋的字元位置。

傳回

與輸入字串相同的新字串 (不同之處是取代字串會取代每一個相符的字串)。 如果規則運算式模式在目前執行個體中沒有符合項目,方法會傳回未變更的目前執行個體。

例外狀況

inputevaluatornull

startat 小於零或大於 input 的長度。

發生逾時。 如需逾時的詳細資訊,請參閱<備註>一節。

備註

Regex.Replace(String, MatchEvaluator, Int32, Int32)如果下列任一條件成立,方法就適合取代正則運算式比對:

  • 取代字串無法立即由正則運算式取代模式指定。
  • 取代字串會產生比對字串上完成的一些處理。
  • 取代字串會產生條件式處理。

方法相當於呼叫 Regex.Matches(String, Int32) 方法,並將傳 MatchCollection 回集合中的第一個 countMatch 物件傳遞至 evaluator 委派。

如需 的詳細資訊 startat ,請參閱 的一 Match(String, Int32) 節。

正則運算式是由目前 Regex 物件的建構函式所定義的模式。

參數 evaluator 是您定義之自訂方法的委派,而且會檢查每個相符專案。 自訂方法必須具有下列簽章,才能符合 MatchEvaluator 委派。

public string MatchEvaluatorMethod(Match match)
Public Function MatchEvaluatorMethod(match As Match) As String

您的自訂方法會傳回字串,以取代相符的輸入。

如果取代作業的執行時間超出 RegexMatchTimeoutException 建構函式所指定的逾時間隔,就會擲回 Regex.Regex(String, RegexOptions, TimeSpan) 例外狀況。 呼叫建構函式時若未設定逾時間隔,則如果作業超過為建立 Regex 物件的應用程式定義域設定的任何逾時值,就會擲回例外狀況。 如果在 Regex 建構函式呼叫或應用程式定義域的屬性中未定義任何逾時,或逾時值是 Regex.InfiniteMatchTimeout,則不擲回任何例外狀況

因為方法在沒有相符專案時傳回 input 不變,所以您可以使用 Object.ReferenceEquals 方法來判斷方法是否已對輸入字串進行任何取代。

另請參閱

適用於

Replace(String, String, String)

在指定的輸入字串中,使用指定的取代字串來取代符合指定之規則運算式的所有字串。

public:
 static System::String ^ Replace(System::String ^ input, System::String ^ pattern, System::String ^ replacement);
public static string Replace (string input, string pattern, string replacement);
static member Replace : string * string * string -> string
Public Shared Function Replace (input As String, pattern As String, replacement As String) As String

參數

input
String

用來搜尋比對的字串。

pattern
String

要比對的規則運算式模式。

replacement
String

取代字串。

傳回

與輸入字串相同的新字串 (不同之處是取代字串會取代每一個相符的字串)。 如果在目前的執行個體中沒有符合 pattern 的項目,則方法傳回未變更的目前執行個體。

例外狀況

發生規則運算式剖析錯誤。

inputpatternreplacementnull

發生逾時。 如需逾時的詳細資訊,請參閱<備註>一節。

範例

下列範例會定義符合一或多個空白字元的正則運算式 \s+ 。 取代字串 「 」, 會以單一空白字元取代它們。

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = "This is   text with   far  too   much   " + 
                     "white space.";
      string pattern = "\\s+";
      string replacement = " ";
      string result = Regex.Replace(input, pattern, replacement);
      
      Console.WriteLine("Original String: {0}", input);
      Console.WriteLine("Replacement String: {0}", result);                             
   }
}
// The example displays the following output:
//       Original String: This is   text with   far  too   much   white space.
//       Replacement String: This is text with far too much white space.
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim input As String = "This is   text with   far  too   much   " + _
                            "white space."
      Dim pattern As String = "\s+"
      Dim replacement As String = " "
      Dim result As String = Regex.Replace(input, pattern, replacement)
      
      Console.WriteLine("Original String: {0}", input)
      Console.WriteLine("Replacement String: {0}", result)                             
   End Sub
End Module
' The example displays the following output:
'          Original String: This is   text with   far  too   much   white space.
'          Replacement String: This is text with far too much white space.

下列範例會使用 方法, Replace(String, String, String) 將 UNC 路徑中的本機電腦和磁片磁碟機名稱取代為本機檔案路徑。 正則運算式會 Environment.MachineName 使用 屬性來包含本機電腦的名稱,以及 Environment.GetLogicalDrives 包含邏輯磁片磁碟機名稱的方法。 若要成功執行此範例,您應該以本機電腦名稱稱取代常值字串 「MyMachine」。

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      // Get drives available on local computer and form into a single character expression.
      string[] drives = Environment.GetLogicalDrives();
      string driveNames = String.Empty;
      foreach (string drive in drives)
         driveNames += drive.Substring(0,1);
      // Create regular expression pattern dynamically based on local machine information.
      string pattern = @"\\\\(?i:" + Environment.MachineName + @")(?:\.\w+)*\\((?i:[" + driveNames + @"]))\$";

      string replacement = "$1:";
      string[] uncPaths = { @"\\MyMachine.domain1.mycompany.com\C$\ThingsToDo.txt", 
                            @"\\MyMachine\c$\ThingsToDo.txt", 
                            @"\\MyMachine\d$\documents\mydocument.docx" }; 
      
      foreach (string uncPath in uncPaths)
      {
         Console.WriteLine("Input string: " + uncPath);
         Console.WriteLine("Returned string: " + Regex.Replace(uncPath, pattern, replacement));
         Console.WriteLine();
      }
   }
}
// The example displays the following output if run on a machine whose name is
// MyMachine:
//    Input string: \\MyMachine.domain1.mycompany.com\C$\ThingsToTo.txt
//    Returned string: C:\ThingsToDo.txt
//    
//    Input string: \\MyMachine\c$\ThingsToDo.txt
//    Returned string: c:\ThingsToDo.txt
//    
//    Input string: \\MyMachine\d$\documents\mydocument.docx
//    Returned string: d:\documents\mydocument.docx
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      ' Get drives available on local computer and form into a single character expression.
      Dim drives() As String = Environment.GetLogicalDrives()
      Dim driveNames As String = Nothing
      For Each drive As String In drives
         driveNames += drive.Substring(0,1)
      Next
      ' Create regular expression pattern dynamically based on local machine information.
      Dim pattern As String = "\\\\(?i:" + Environment.MachineName + ")(?:\.\w+)*\\((?i:[" + driveNames + "]))\$"

      Dim replacement As String = "$1:"
      Dim uncPaths() AS String = {"\\MyMachine.domain1.mycompany.com\C$\ThingsToDo.txt", _
                                  "\\MyMachine\c$\ThingsToDo.txt", _
                                  "\\MyMachine\d$\documents\mydocument.docx" } 
      
      For Each uncPath As String In uncPaths
         Console.WriteLine("Input string: " + uncPath)
         Console.WriteLine("Returned string: " + Regex.Replace(uncPath, pattern, replacement))
         Console.WriteLine()
      Next
   End Sub
End Module
' The example displays the following output if run on a machine whose name is
' MyMachine:
'    Input string: \\MyMachine.domain1.mycompany.com\C$\ThingsToTo.txt
'    Returned string: C:\ThingsToDo.txt
'    
'    Input string: \\MyMachine\c$\ThingsToDo.txt
'    Returned string: c:\ThingsToDo.txt
'    
'    Input string: \\MyMachine\d$\documents\mydocument.docx
'    Returned string: d:\documents\mydocument.docx

正則運算式模式是由下列運算式所定義:

"\\\\(?i:" + Environment.MachineName + ")(?:\.\w+)*\\((?i:[" + driveNames + "]))\$"

下表顯示規則運算式模式的解譯方式。

模式 描述
\\\\ 比對兩個連續反斜線 (\) 字元。 因為反斜線字元會解譯為逸出字元,所以每個反斜線都必須以另一個反斜線逸出。
(?i:" + Environment.MachineName + ") 執行 屬性所 Environment.MachineName 傳回之字串不區分大小寫的比對。
(?:\.\w+)* 比對句號 (.) 字元後面接著一或多個字字元。 此比對可能會發生零次或多次。 未擷取相符的子運算式。
\\ 比對反斜線 (\) 字元。
((?i:[" + driveNames + "])) 對由個別磁碟機號組成的字元類別執行不區分大小寫的比對。 這是第一個擷取的子運算式。
\$ 比對常值貨幣符號 ($) 字元。

取代模式 $1 會以第一個擷取的子運算式取代整個相符專案。 也就是說,它會以磁碟機號取代 UNC 電腦和磁片磁碟機名稱。

備註

靜態 Replace 方法相當於使用指定的正則運算式模式建構 Regex 物件,並呼叫 實例方法 Replace

pattern 參數包含規則運算式語言項目,以透過符號描述要比對的字串。 如需正則運算式的詳細資訊,請參閱 .NET 正則運算式正則運算式語言 - 快速參考。 搜尋相符專案會從字串的 input 開頭開始。

參數 replacement 會指定要取代 中每個相符項的 input 字串。 replacement 可以包含常值文字和 替代的任何組合。 例如,取代模式 a*${test}b 會插入字串 「a*」,後面接著擷取群組比對的子字串 test ,如果有的話,後面接著字串 「b」。 * 字元在取代模式中無法辨識為中繼字元。

注意

替代是替代模式中唯一可辨識的正則運算式語言專案。 所有其他正則運算式語言專案,包括 字元逸出,只能在正則運算式模式中允許,而且無法在取代模式中辨識。

如果取代作業的執行時間超出為呼叫方法的應用程式定義域指定的逾時間隔,就會擲回 RegexMatchTimeoutException 例外狀況。 如果在應用程式定義域的屬性中未定義任何逾時,或逾時值是 Regex.InfiniteMatchTimeout,則不擲回任何例外狀況。

因為如果沒有相符專案,方法會傳回 input 未變更,所以您可以使用 Object.ReferenceEquals 方法來判斷方法是否已對輸入字串進行任何取代。

給呼叫者的注意事項

這個方法的逾時間隔等於呼叫這個方法的應用程式定義域的預設逾時值。 如果未針對應用程式定義域定義逾時值,則使用值 InfiniteMatchTimeout,使方法不會逾時。 取代模式比 Replace(String, String, String, RegexOptions, TimeSpan) 對的建議靜態方法是 ,可讓您設定逾時間隔。

另請參閱

適用於

Replace(String, String, MatchEvaluator, RegexOptions, TimeSpan)

在指定的輸入字串中,使用 MatchEvaluator 委派所傳回的字串,取代所有與指定之規則運算式相符的子字串。 如果沒有找到相符項目,其他參數會指定修改比對作業的選項和逾時間隔。

public:
 static System::String ^ Replace(System::String ^ input, System::String ^ pattern, System::Text::RegularExpressions::MatchEvaluator ^ evaluator, System::Text::RegularExpressions::RegexOptions options, TimeSpan matchTimeout);
public static string Replace (string input, string pattern, System.Text.RegularExpressions.MatchEvaluator evaluator, System.Text.RegularExpressions.RegexOptions options, TimeSpan matchTimeout);
static member Replace : string * string * System.Text.RegularExpressions.MatchEvaluator * System.Text.RegularExpressions.RegexOptions * TimeSpan -> string
Public Shared Function Replace (input As String, pattern As String, evaluator As MatchEvaluator, options As RegexOptions, matchTimeout As TimeSpan) As String

參數

input
String

用來搜尋比對的字串。

pattern
String

要比對的規則運算式模式。

evaluator
MatchEvaluator

檢查每個符合項目並傳回原始符合字串或取代字串的自訂方法。

options
RegexOptions

列舉值的位元組合,提供用於比對的選項。

matchTimeout
TimeSpan

逾時間隔,若要表示此方法不應逾時則為 InfiniteMatchTimeout

傳回

與輸入字串相同的新字串 (不同之處是取代字串會取代每一個相符的字串)。 如果在目前的執行個體中沒有符合 pattern 的項目,則方法傳回未變更的目前執行個體。

例外狀況

發生規則運算式剖析錯誤。

inputpatternevaluatornull

options 不是 RegexOptions 值的有效位元組合。

-或-

matchTimeout 為負數、零或約大於 24 天。

發生逾時。 如需逾時的詳細資訊,請參閱<備註>一節。

範例

下列範例使用正則運算式從字串擷取個別字組,然後使用 MatchEvaluator 委派呼叫名為 WordScramble 的方法,以拼字中的個別字母。 若要這樣做,方法會 WordScramble 建立包含相符字元的陣列。 它也會建立平行陣列,以隨機浮點數填入。 陣列會藉由呼叫 Array.Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>) 方法來排序,而且已排序的陣列會當做類別建構函式的 String 引數提供。 方法接著會傳回這個新建立的 WordScramble 字串。 正則運算式模式 \w+ 會比對一或多個文字字元;正則運算式引擎會繼續將字元新增至相符專案,直到遇到非單字字元,例如空白字元。 方法的呼叫 Replace(String, String, MatchEvaluator, RegexOptions) 包含 RegexOptions.IgnorePatternWhitespace 選項,因此正則運算式引擎會忽略正則運算式模式 \w+ # Matches all the characters in a word. 中的批註。

using System;
using System.Collections;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string words = "letter alphabetical missing lack release " + 
                     "penchant slack acryllic laundry cease";
      string pattern = @"\w+  # Matches all the characters in a word.";                            
      MatchEvaluator evaluator = new MatchEvaluator(WordScrambler);
      Console.WriteLine("Original words:");
      Console.WriteLine(words);
      Console.WriteLine();
      try {
         Console.WriteLine("Scrambled words:");
         Console.WriteLine(Regex.Replace(words, pattern, evaluator, 
                                         RegexOptions.IgnorePatternWhitespace,
                                         TimeSpan.FromSeconds(.25)));      
      }
      catch (RegexMatchTimeoutException) {
         Console.WriteLine("Word Scramble operation timed out.");
         Console.WriteLine("Returned words:");
      }
   }

   public static string WordScrambler(Match match)
   {
      int arraySize = match.Value.Length;
      // Define two arrays equal to the number of letters in the match.
      double[] keys = new double[arraySize];
      char[] letters = new char[arraySize];
      
      // Instantiate random number generator'
      Random rnd = new Random();
      
      for (int ctr = 0; ctr < match.Value.Length; ctr++)
      {
         // Populate the array of keys with random numbers.
         keys[ctr] = rnd.NextDouble();
         // Assign letter to array of letters.
         letters[ctr] = match.Value[ctr];
      }         
      Array.Sort(keys, letters, 0, arraySize, Comparer.Default);      
      return new String(letters);
   }
}
// The example displays output similar to the following:
//    Original words:
//    letter alphabetical missing lack release penchant slack acryllic laundry cease
//    
//    Scrambled words:
//    etlert liahepalbcat imsgsni alkc ereelsa epcnnaht lscak cayirllc alnyurd ecsae
Imports System.Collections
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim words As String = "letter alphabetical missing lack release " + _
                            "penchant slack acryllic laundry cease"
      Dim pattern As String = "\w+  # Matches all the characters in a word."                            
      Dim evaluator As MatchEvaluator = AddressOf WordScrambler
      Console.WriteLine("Original words:")
      Console.WriteLine(words)
      Try
         Console.WriteLine("Scrambled words:")
         Console.WriteLine(Regex.Replace(words, pattern, evaluator,
                                         RegexOptions.IgnorePatternWhitespace,
                                         TimeSpan.FromSeconds(.25)))      
      Catch e As RegexMatchTimeoutException
         Console.WriteLine("Word Scramble operation timed out.")
         Console.WriteLine("Returned words:")
      End Try   
   End Sub
   
   Public Function WordScrambler(match As Match) As String
      Dim arraySize As Integer = match.Value.Length - 1
      ' Define two arrays equal to the number of letters in the match.
      Dim keys(arraySize) As Double
      Dim letters(arraySize) As Char
      
      ' Instantiate random number generator'
      Dim rnd As New Random()
      
      For ctr As Integer = 0 To match.Value.Length - 1
         ' Populate the array of keys with random numbers.
         keys(ctr) = rnd.NextDouble()
         ' Assign letter to array of letters.
         letters(ctr) = match.Value.Chars(ctr)
      Next         
      Array.Sort(keys, letters, 0, arraySize, Comparer.Default)      
      Return New String(letters)
   End Function
End Module
' The example displays output similar to the following:
'    Original words:
'    letter alphabetical missing lack release penchant slack acryllic laundry cease
'    
'    Scrambled words:
'    etlert liahepalbcat imsgsni alkc ereelsa epcnnaht lscak cayirllc alnyurd ecsae

備註

Regex.Replace(String, String, MatchEvaluator, RegexOptions)如果下列任一條件成立,此方法就很適合用來取代正則運算式比對:

  • 如果正則運算式取代模式無法立即指定取代字串。

  • 如果取代字串會產生在相符字串上執行的一些處理。

  • 如果取代字串結果來自條件式處理。

方法相當於呼叫 方法, Regex.Matches(String, String, RegexOptions) 並將傳 MatchCollection 回集合中的每個物件傳遞 Matchevaluator 委派。

pattern 參數包含規則運算式語言項目,以透過符號描述要比對的字串。 如需正則運算式的詳細資訊,請參閱 .NET 正則運算式正則運算式語言 - 快速參考

參數 evaluator 是您定義之自訂方法的委派,會檢查每個相符專案。 自訂方法必須具有下列簽章,才能符合 MatchEvaluator 委派。

public string MatchEvaluatorMethod(Match match)
Public Function MatchEvaluatorMethod(match As Match) As String

您的自訂方法會傳回字串,以取代相符的輸入。

如果為 RightToLeft 參數指定 options,搜尋符合項目會從輸入字串結尾開始向左移動,否則,搜尋會從輸入字串開頭開始向右移動。

參數 matchTimeout 會指定模式比對方法在逾時之前應該嘗試尋找相符專案的時間長度。設定逾時間隔可防止依賴過多回溯的正則運算式出現在「處理包含接近相符專案的輸入時停止回應」。 如需詳細資訊,請參閱正則運算式和回溯的最佳做法。 如果該時間間隔中找不到相符專案,方法會 RegexMatchTimeoutException 擲回例外狀況。 matchTimeout 會覆寫針對方法執行所在應用程式域所定義的任何預設逾時值。

因為如果沒有相符專案,方法會傳回 input 未變更,所以您可以使用 Object.ReferenceEquals 方法來判斷方法是否已對輸入字串進行任何取代。

給呼叫者的注意事項

我們建議您將 matchTimeout 參數設定為適當的值,例如兩秒。 如果您藉由指定 InfiniteMatchTimeout 來停用逾時,正則運算式引擎會提供稍微更好的效能。 不過,您應該只在下列情況下停用逾時:

  • 當正則運算式處理的輸入衍生自已知且受信任的來源,或由靜態文字所組成時。 這不包括使用者動態輸入的文字。

  • 當正則運算式模式經過徹底測試,以確保其有效率地處理相符專案、非相符專案和接近相符專案。

  • 當正則運算式模式不包含已知在處理接近相符專案時造成過多回溯的語言專案時。

另請參閱

適用於

Replace(String, String, MatchEvaluator, RegexOptions)

在指定的輸入字串中,使用由 MatchEvaluator 委派所傳回的字串,取代所有與指定之規則運算式相符的字串。 指定的選項會修改符合的作業。

public:
 static System::String ^ Replace(System::String ^ input, System::String ^ pattern, System::Text::RegularExpressions::MatchEvaluator ^ evaluator, System::Text::RegularExpressions::RegexOptions options);
public static string Replace (string input, string pattern, System.Text.RegularExpressions.MatchEvaluator evaluator, System.Text.RegularExpressions.RegexOptions options);
static member Replace : string * string * System.Text.RegularExpressions.MatchEvaluator * System.Text.RegularExpressions.RegexOptions -> string
Public Shared Function Replace (input As String, pattern As String, evaluator As MatchEvaluator, options As RegexOptions) As String

參數

input
String

用來搜尋比對的字串。

pattern
String

要比對的規則運算式模式。

evaluator
MatchEvaluator

檢查每個符合項目並傳回原始符合字串或取代字串的自訂方法。

options
RegexOptions

列舉值的位元組合,提供用於比對的選項。

傳回

與輸入字串相同的新字串 (不同之處是取代字串會取代每一個相符的字串)。 如果在目前的執行個體中沒有符合 pattern 的項目,則方法傳回未變更的目前執行個體。

例外狀況

發生規則運算式剖析錯誤。

inputpatternevaluatornull

options 不是 RegexOptions 值的有效位元組合。

發生逾時。 如需逾時的詳細資訊,請參閱<備註>一節。

範例

下列範例使用正則運算式從字串擷取個別字組,然後使用 MatchEvaluator 委派呼叫名為 WordScramble 的方法,以拼字中的個別字母。 若要這樣做,方法會 WordScramble 建立包含相符字元的陣列。 它也會建立平行陣列,以隨機浮點數填入。 陣列會藉由呼叫 Array.Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>) 方法來排序,而且已排序的陣列會當做類別建構函式的 String 引數提供。 方法接著會傳回這個新建立的 WordScramble 字串。 正則運算式模式 \w+ 會比對一或多個文字字元;正則運算式引擎會繼續將字元新增至相符專案,直到遇到非單字字元,例如空白字元。 方法的呼叫 Replace(String, String, MatchEvaluator, RegexOptions) 包含 RegexOptions.IgnorePatternWhitespace 選項,因此正則運算式引擎會忽略正則運算式模式 \w+ # Matches all the characters in a word. 中的批註。

using System;
using System.Collections;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string words = "letter alphabetical missing lack release " + 
                     "penchant slack acryllic laundry cease";
      string pattern = @"\w+  # Matches all the characters in a word.";                            
      MatchEvaluator evaluator = new MatchEvaluator(WordScrambler);
      Console.WriteLine("Original words:");
      Console.WriteLine(words);
      Console.WriteLine();
      Console.WriteLine("Scrambled words:");
      Console.WriteLine(Regex.Replace(words, pattern, evaluator, 
                                      RegexOptions.IgnorePatternWhitespace));      
   }

   public static string WordScrambler(Match match)
   {
      int arraySize = match.Value.Length;
      // Define two arrays equal to the number of letters in the match.
      double[] keys = new double[arraySize];
      char[] letters = new char[arraySize];
      
      // Instantiate random number generator'
      Random rnd = new Random();
      
      for (int ctr = 0; ctr < match.Value.Length; ctr++)
      {
         // Populate the array of keys with random numbers.
         keys[ctr] = rnd.NextDouble();
         // Assign letter to array of letters.
         letters[ctr] = match.Value[ctr];
      }         
      Array.Sort(keys, letters, 0, arraySize, Comparer.Default);      
      return new String(letters);
   }
}
// The example displays output similar to the following:
//    Original words:
//    letter alphabetical missing lack release penchant slack acryllic laundry cease
//    
//    Scrambled words:
//    etlert liahepalbcat imsgsni alkc ereelsa epcnnaht lscak cayirllc alnyurd ecsae
Imports System.Collections
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim words As String = "letter alphabetical missing lack release " + _
                            "penchant slack acryllic laundry cease"
      Dim pattern As String = "\w+  # Matches all the characters in a word."                            
      Dim evaluator As MatchEvaluator = AddressOf WordScrambler
      Console.WriteLine("Original words:")
      Console.WriteLine(words)
      Console.WriteLine("Scrambled words:")
      Console.WriteLine(Regex.Replace(words, pattern, evaluator,
                                      RegexOptions.IgnorePatternWhitespace))      
   End Sub
   
   Public Function WordScrambler(match As Match) As String
      Dim arraySize As Integer = match.Value.Length - 1
      ' Define two arrays equal to the number of letters in the match.
      Dim keys(arraySize) As Double
      Dim letters(arraySize) As Char
      
      ' Instantiate random number generator'
      Dim rnd As New Random()
      
      For ctr As Integer = 0 To match.Value.Length - 1
         ' Populate the array of keys with random numbers.
         keys(ctr) = rnd.NextDouble()
         ' Assign letter to array of letters.
         letters(ctr) = match.Value.Chars(ctr)
      Next         
      Array.Sort(keys, letters, 0, arraySize, Comparer.Default)      
      Return New String(letters)
   End Function
End Module
' The example displays output similar to the following:
'    Original words:
'    letter alphabetical missing lack release penchant slack acryllic laundry cease
'    
'    Scrambled words:
'    etlert liahepalbcat imsgsni alkc ereelsa epcnnaht lscak cayirllc alnyurd ecsae

備註

如果下列任一條件成立,此方法 Regex.Replace(String, String, MatchEvaluator, RegexOptions) 就很適合用來取代 中的正則運算式比對:

  • 取代字串無法立即由正則運算式取代模式指定。

  • 取代字串會產生比對字串上完成的一些處理。

  • 取代字串會產生條件式處理的結果。

方法相當於呼叫 方法, Regex.Matches(String, String, RegexOptions) 並將傳 MatchCollection 回集合中的每個物件傳遞 Matchevaluator 委派。

pattern 參數包含規則運算式語言項目,以透過符號描述要比對的字串。 如需正則運算式的詳細資訊,請參閱 .NET 正則運算式正則運算式語言 - 快速參考

參數 evaluator 是您定義之自訂方法的委派,會檢查每個相符專案。 自訂方法必須具有下列簽章,才能符合 MatchEvaluator 委派。

public string MatchEvaluatorMethod(Match match)
Public Function MatchEvaluatorMethod(match As Match) As String

您的自訂方法會傳回字串,以取代相符的輸入。

如果為 RightToLeft 參數指定 options,搜尋符合項目會從輸入字串結尾開始向左移動,否則,搜尋會從輸入字串開頭開始向右移動。

如果取代作業的執行時間超出為呼叫方法的應用程式定義域指定的逾時間隔,就會擲回 RegexMatchTimeoutException 例外狀況。 如果在應用程式定義域的屬性中未定義任何逾時,或逾時值是 Regex.InfiniteMatchTimeout,則不擲回任何例外狀況。

因為如果沒有相符專案,方法會傳回 input 未變更,所以您可以使用 Object.ReferenceEquals 方法來判斷方法是否已對輸入字串進行任何取代。

另請參閱

適用於

Replace(String, String, String, RegexOptions, TimeSpan)

在指定的輸入字串中,使用指定的取代字串來取代符合指定之規則運算式的所有字串。 如果沒有找到相符項目,其他參數會指定修改比對作業的選項和逾時間隔。

public:
 static System::String ^ Replace(System::String ^ input, System::String ^ pattern, System::String ^ replacement, System::Text::RegularExpressions::RegexOptions options, TimeSpan matchTimeout);
public static string Replace (string input, string pattern, string replacement, System.Text.RegularExpressions.RegexOptions options, TimeSpan matchTimeout);
static member Replace : string * string * string * System.Text.RegularExpressions.RegexOptions * TimeSpan -> string
Public Shared Function Replace (input As String, pattern As String, replacement As String, options As RegexOptions, matchTimeout As TimeSpan) As String

參數

input
String

用來搜尋比對的字串。

pattern
String

要比對的規則運算式模式。

replacement
String

取代字串。

options
RegexOptions

列舉值的位元組合,提供用於比對的選項。

matchTimeout
TimeSpan

逾時間隔,若要表示此方法不應逾時則為 InfiniteMatchTimeout

傳回

與輸入字串相同的新字串 (不同之處是取代字串會取代每一個相符的字串)。 如果在目前的執行個體中沒有符合 pattern 的項目,則方法傳回未變更的目前執行個體。

例外狀況

發生規則運算式剖析錯誤。

inputpatternreplacementnull

options 不是 RegexOptions 值的有效位元組合。

-或-

matchTimeout 為負數、零或約大於 24 天。

發生逾時。 如需逾時的詳細資訊,請參閱<備註>一節。

範例

下列範例會 Replace(String, String, String, RegexOptions, TimeSpan) 使用 方法,將 UNC 路徑中的本機電腦和磁片磁碟機名稱取代為本機檔案路徑。 正則運算式會 Environment.MachineName 使用 屬性來包含本機電腦的名稱,以及 Environment.GetLogicalDrives 包含邏輯磁碟機名稱的方法。 所有正則運算式字串比較不區分大小寫,如果無法在 0.5 秒中找到相符專案,則任何單一取代作業都會逾時。 若要成功執行此範例,您應該以本機電腦名稱稱取代常值字串 「MyMachine」。

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      // Get drives available on local computer and form into a single character expression.
      string[] drives = Environment.GetLogicalDrives();
      string driveNames = String.Empty;
      foreach (string drive in drives)
         driveNames += drive.Substring(0,1);
      // Create regular expression pattern dynamically based on local machine information.
      string pattern = @"\\\\" + Environment.MachineName + @"(?:\.\w+)*\\([" + driveNames + @"])\$";

      string replacement = "$1:";
      string[] uncPaths = { @"\\MyMachine.domain1.mycompany.com\C$\ThingsToDo.txt", 
                            @"\\MyMachine\c$\ThingsToDo.txt", 
                            @"\\MyMachine\d$\documents\mydocument.docx" }; 
      
      foreach (string uncPath in uncPaths)
      {
         Console.WriteLine("Input string: " + uncPath);
         string localPath = null;
         try {
            localPath = Regex.Replace(uncPath, pattern, replacement, 
                                      RegexOptions.IgnoreCase,
                                      TimeSpan.FromSeconds(0.5));
            Console.WriteLine("Returned string: " + localPath);
         }
         catch (RegexMatchTimeoutException) {
            Console.WriteLine("The replace operation timed out.");
            Console.WriteLine("Returned string: " + localPath);
            if (uncPath.Equals(localPath)) 
               Console.WriteLine("Equal to original path.");
            else
               Console.WriteLine("Original string: " + uncPath);
         }
         Console.WriteLine();
      }
   }
}
// The example displays the following output if run on a machine whose name is
// MyMachine:
//    Input string: \\MyMachine.domain1.mycompany.com\C$\ThingsToTo.txt
//    Returned string: C:\ThingsToDo.txt
//    
//    Input string: \\MyMachine\c$\ThingsToDo.txt
//    Returned string: c:\ThingsToDo.txt
//    
//    Input string: \\MyMachine\d$\documents\mydocument.docx
//    Returned string: d:\documents\mydocument.docx
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      ' Get drives available on local computer and form into a single character expression.
      Dim drives() As String = Environment.GetLogicalDrives()
      Dim driveNames As String = Nothing
      For Each drive As String In drives
         driveNames += drive.Substring(0,1)
      Next
      ' Create regular expression pattern dynamically based on local machine information.
      Dim pattern As String = "\\\\" + Environment.MachineName + "(?:\.\w+)*\\([" + driveNames + "])\$"

      Dim replacement As String = "$1:"
      Dim uncPaths() AS String = {"\\MyMachine.domain1.mycompany.com\C$\ThingsToDo.txt", _
                                  "\\MyMachine\c$\ThingsToDo.txt", _
                                  "\\MyMachine\d$\documents\mydocument.docx" } 
      
      For Each uncPath As String In uncPaths
         Console.WriteLine("Input string: " + uncPath)
         Dim localPath As String = Nothing
         Try
            localPath = Regex.Replace(uncPath, pattern, replacement, 
                                                               RegexOptions.IgnoreCase,
                                                               TimeSpan.FromSeconds(0.5))
            Console.WriteLine("Returned string: " + localPath)         
         Catch e As RegexMatchTimeoutException
            Console.WriteLine("The replace operation timed out.")
            Console.WriteLine("Returned string: " + localPath)
            If uncPath.Equals(localPath) Then 
               Console.WriteLine("Equal to original path.")
            Else
               Console.WriteLine("Original string: " + uncPath)
            End If
         End Try         
         Console.WriteLine()
      Next
   End Sub
End Module
' The example displays the following output if run on a machine whose name is
' MyMachine:
'    Input string: \\MyMachine.domain1.mycompany.com\C$\ThingsToTo.txt
'    Returned string: C:\ThingsToDo.txt
'    
'    Input string: \\MyMachine\c$\ThingsToDo.txt
'    Returned string: c:\ThingsToDo.txt
'    
'    Input string: \\MyMachine\d$\documents\mydocument.docx
'    Returned string: d:\documents\mydocument.docx

正則運算式模式是由下列運算式所定義:

"\\\\" + Environment.MachineName + "(?:\.\w+)*\\([" + driveNames + "])\$"

下表顯示規則運算式模式的解譯方式。

模式 描述
\\\\ 比對 \ 兩個連續反斜線 () 字元。 由於反斜線字元會解譯為逸出字元,因此每個反斜線都必須以另一個反斜線逸出。
+ Environment.MachineName + 比對 屬性所傳回的 Environment.MachineName 字串。
(?:\.\w+)* 比對 . 句號 () 字元後面接著一或多個文字字元。 此比對可能會發生零次或多次。 不會擷取相符的子運算式。
\\ 比對反斜線 (\) 字元。
([" + driveNames + "]) 比對由個別磁碟機號組成的字元類別。 此比對是第一個擷取的子運算式。
\$ 比對常值貨幣符號 ($) 字元。

取代模式 $1 會將整個相符專案取代為第一個擷取的子運算式。 也就是說,它會以磁碟機號取代 UNC 機器和磁片磁碟機名稱。

備註

靜態 Replace 方法相當於使用指定的正則運算式模式建構 Regex 物件,並呼叫 實例方法 Replace

pattern 參數包含規則運算式語言項目,以透過符號描述要比對的字串。 如需正則運算式的詳細資訊,請參閱 .NET 正則運算式正則運算式語言 - 快速參考。 如果為 RightToLeft 參數指定 options,搜尋符合項目會從輸入字串結尾開始向左移動,否則,搜尋會從輸入字串開頭開始向右移動。

參數 replacement 會指定要取代 中每個相符項的 input 字串。 replacement 可以包含常值文字和 替代的任何組合。 例如,取代模式 a*${test}b 會插入字串 「a*」,後面接著擷取群組比對的子字串 test ,如果有的話,後面接著字串 「b」。 * 字元在取代模式中無法辨識為中繼字元。

注意

替代是替代模式中唯一可辨識的正則運算式語言專案。 所有其他正則運算式語言專案,包括 字元逸出,只能在正則運算式模式中允許,而且無法在取代模式中辨識。

參數 matchTimeout 會指定模式比對方法在逾時之前應該嘗試尋找相符專案的時間長度。設定逾時間隔可防止依賴過多回溯的正則運算式在處理包含接近相符專案的輸入時停止回應。 如需詳細資訊,請參閱正則運算式和回溯的最佳做法。 如果該時間間隔中找不到相符專案,方法會 RegexMatchTimeoutException 擲回例外狀況。 matchTimeout 會覆寫針對方法執行所在應用程式域所定義的任何預設逾時值。

因為如果沒有相符專案,方法會傳回 input 未變更,所以您可以使用 Object.ReferenceEquals 方法來判斷方法是否已對輸入字串進行任何取代。

給呼叫者的注意事項

我們建議您將 matchTimeout 參數設定為適當的值,例如兩秒。 如果您藉由指定 InfiniteMatchTimeout 來停用逾時,正則運算式引擎會提供稍微更好的效能。 不過,您應該只在下列情況下停用逾時:

  • 當正則運算式處理的輸入衍生自已知且受信任的來源,或由靜態文字所組成時。 這不包括使用者動態輸入的文字。

  • 當正則運算式模式經過徹底測試,以確保其有效率地處理相符專案、非相符專案和接近相符專案。

  • 當正則運算式模式不包含已知在處理接近相符專案時造成過多回溯的語言專案時。

另請參閱

適用於

Replace(String, String, String, RegexOptions)

在指定的輸入字串中,使用指定的取代字串來取代符合指定之規則運算式的所有字串。 指定的選項會修改符合的作業。

public:
 static System::String ^ Replace(System::String ^ input, System::String ^ pattern, System::String ^ replacement, System::Text::RegularExpressions::RegexOptions options);
public static string Replace (string input, string pattern, string replacement, System.Text.RegularExpressions.RegexOptions options);
static member Replace : string * string * string * System.Text.RegularExpressions.RegexOptions -> string
Public Shared Function Replace (input As String, pattern As String, replacement As String, options As RegexOptions) As String

參數

input
String

用來搜尋比對的字串。

pattern
String

要比對的規則運算式模式。

replacement
String

取代字串。

options
RegexOptions

列舉值的位元組合,提供用於比對的選項。

傳回

與輸入字串相同的新字串 (不同之處是取代字串會取代每一個相符的字串)。 如果在目前的執行個體中沒有符合 pattern 的項目,則方法傳回未變更的目前執行個體。

例外狀況

發生規則運算式剖析錯誤。

inputpatternreplacementnull

options 不是 RegexOptions 值的有效位元組合。

發生逾時。 如需逾時的詳細資訊,請參閱<備註>一節。

範例

下列範例會 Replace(String, String, String, RegexOptions) 使用 方法,將 UNC 路徑中的本機電腦和磁片磁碟機名稱取代為本機檔案路徑。 正則運算式會 Environment.MachineName 使用 屬性來包含本機電腦的名稱,以及 Environment.GetLogicalDrives 包含邏輯磁碟機名稱的方法。 所有正則運算式字串比較不區分大小寫。 若要成功執行此範例,您應該以本機電腦名稱稱取代常值字串 「MyMachine」。

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      // Get drives available on local computer and form into a single character expression.
      string[] drives = Environment.GetLogicalDrives();
      string driveNames = String.Empty;
      foreach (string drive in drives)
         driveNames += drive.Substring(0,1);
      // Create regular expression pattern dynamically based on local machine information.
      string pattern = @"\\\\" + Environment.MachineName + @"(?:\.\w+)*\\([" + driveNames + @"])\$";

      string replacement = "$1:";
      string[] uncPaths = { @"\\MyMachine.domain1.mycompany.com\C$\ThingsToDo.txt", 
                            @"\\MyMachine\c$\ThingsToDo.txt", 
                            @"\\MyMachine\d$\documents\mydocument.docx" }; 
      
      foreach (string uncPath in uncPaths)
      {
         Console.WriteLine("Input string: " + uncPath);
         Console.WriteLine("Returned string: " + Regex.Replace(uncPath, pattern, replacement, RegexOptions.IgnoreCase));
         Console.WriteLine();
      }
   }
}
// The example displays the following output if run on a machine whose name is
// MyMachine:
//    Input string: \\MyMachine.domain1.mycompany.com\C$\ThingsToTo.txt
//    Returned string: C:\ThingsToDo.txt
//    
//    Input string: \\MyMachine\c$\ThingsToDo.txt
//    Returned string: c:\ThingsToDo.txt
//    
//    Input string: \\MyMachine\d$\documents\mydocument.docx
//    Returned string: d:\documents\mydocument.docx
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      ' Get drives available on local computer and form into a single character expression.
      Dim drives() As String = Environment.GetLogicalDrives()
      Dim driveNames As String = Nothing
      For Each drive As String In drives
         driveNames += drive.Substring(0,1)
      Next
      ' Create regular expression pattern dynamically based on local machine information.
      Dim pattern As String = "\\\\" + Environment.MachineName + "(?:\.\w+)*\\([" + driveNames + "])\$"

      Dim replacement As String = "$1:"
      Dim uncPaths() AS String = {"\\MyMachine.domain1.mycompany.com\C$\ThingsToDo.txt", _
                                  "\\MyMachine\c$\ThingsToDo.txt", _
                                  "\\MyMachine\d$\documents\mydocument.docx" } 
      
      For Each uncPath As String In uncPaths
         Console.WriteLine("Input string: " + uncPath)
         Console.WriteLine("Returned string: " + Regex.Replace(uncPath, pattern, replacement, RegexOptions.IgnoreCase))
         Console.WriteLine()
      Next
   End Sub
End Module
' The example displays the following output if run on a machine whose name is
' MyMachine:
'    Input string: \\MyMachine.domain1.mycompany.com\C$\ThingsToTo.txt
'    Returned string: C:\ThingsToDo.txt
'    
'    Input string: \\MyMachine\c$\ThingsToDo.txt
'    Returned string: c:\ThingsToDo.txt
'    
'    Input string: \\MyMachine\d$\documents\mydocument.docx
'    Returned string: d:\documents\mydocument.docx

正則運算式模式是由下列運算式所定義:

"\\\\" + Environment.MachineName + "(?:\.\w+)*\\([" + driveNames + "])\$"

下表顯示規則運算式模式的解譯方式。

模式 描述
\\\\ 比對 \ 兩個連續反斜線 () 字元。 由於反斜線字元會解譯為逸出字元,因此每個反斜線都必須以另一個反斜線逸出。
+ Environment.MachineName + 比對 屬性所傳回的 Environment.MachineName 字串。
(?:\.\w+)* 比對 . 句號 () 字元後面接著一或多個文字字元。 此比對可能會發生零次或多次。 不會擷取相符的子運算式。
\\ 比對反斜線 (\) 字元。
([" + driveNames + "]) 比對由個別磁碟機號組成的字元類別。 此比對是第一個擷取的子運算式。
\$ 比對常值貨幣符號 ($) 字元。

取代模式 $1 會將整個相符專案取代為第一個擷取的子運算式。 也就是說,它會以磁碟機號取代 UNC 機器和磁片磁碟機名稱。

備註

靜態 Replace 方法相當於使用指定的正則運算式模式建構 Regex 物件,並呼叫 實例方法 Replace

pattern 參數包含規則運算式語言項目,以透過符號描述要比對的字串。 如需正則運算式的詳細資訊,請參閱 .NET 正則運算式正則運算式語言 - 快速參考。 如果為 RightToLeft 參數指定 options,搜尋符合項目會從輸入字串結尾開始向左移動,否則,搜尋會從輸入字串開頭開始向右移動。

參數 replacement 會指定要取代 中每個相符項的 input 字串。 replacement 可以包含常值文字和 替代的任何組合。 例如,取代模式 a*${test}b 會插入字串 「a*」,後面接著與擷取群組相符 test 的子字串,如果有的話,後面接著字串 「b」。 * 字元在取代模式中無法辨識為中繼字元。

注意

替代是取代模式中唯一辨識的正則運算式語言專案。 所有其他正則運算式語言專案,包括 字元逸出,只能在正則運算式模式中允許,而且在取代模式中無法辨識。

如果取代作業的執行時間超出為呼叫方法的應用程式定義域指定的逾時間隔,就會擲回 RegexMatchTimeoutException 例外狀況。 如果在應用程式定義域的屬性中未定義任何逾時,或逾時值是 Regex.InfiniteMatchTimeout,則不擲回任何例外狀況。

因為方法在沒有相符專案時傳回 input 不變,所以您可以使用 Object.ReferenceEquals 方法來判斷方法是否已對輸入字串進行任何取代。

給呼叫者的注意事項

這個方法的逾時間隔等於呼叫這個方法的應用程式定義域的預設逾時值。 如果未針對應用程式定義域定義逾時值,則使用值 InfiniteMatchTimeout,使方法不會逾時。 取代模式比 Replace(String, String, String, RegexOptions, TimeSpan) 對的建議靜態方法是 ,可讓您設定逾時間隔。

另請參閱

適用於

Replace(String, MatchEvaluator)

在指定的輸入字串中,使用由 MatchEvaluator 委派所傳回的字串,取代所有與指定之規則運算式相符的字串。

public:
 System::String ^ Replace(System::String ^ input, System::Text::RegularExpressions::MatchEvaluator ^ evaluator);
public string Replace (string input, System.Text.RegularExpressions.MatchEvaluator evaluator);
member this.Replace : string * System.Text.RegularExpressions.MatchEvaluator -> string
Public Function Replace (input As String, evaluator As MatchEvaluator) As String

參數

input
String

用來搜尋比對的字串。

evaluator
MatchEvaluator

檢查每個符合項目並傳回原始符合字串或取代字串的自訂方法。

傳回

與輸入字串相同的新字串 (不同之處是取代字串會取代每一個相符的字串)。 如果規則運算式模式在目前執行個體中沒有符合項目,方法會傳回未變更的目前執行個體。

例外狀況

inputevaluatornull

發生逾時。 如需逾時的詳細資訊,請參閱<備註>一節。

範例

下列程式碼範例會顯示原始字串、比對原始字串中的每個單字、將每個相符專案的第一個字元轉換成大寫,然後顯示轉換的字串。

using System;
using System.Text.RegularExpressions;

class RegExSample
{
    static string CapText(Match m)
    {
        // Get the matched string.
        string x = m.ToString();
        // If the first char is lower case...
        if (char.IsLower(x[0]))
        {
            // Capitalize it.
            return char.ToUpper(x[0]) + x.Substring(1, x.Length - 1);
        }
        return x;
    }

    static void Main()
    {
        string text = "four score and seven years ago";

        Console.WriteLine($"text=[{text}]");

        Regex rx = new Regex(@"\w+");

        string result = rx.Replace(text, new MatchEvaluator(RegExSample.CapText));

        Console.WriteLine($"result=[{result}]");
    }
}
// The example displays the following output:
//       text=[four score and seven years ago]
//       result=[Four Score And Seven Years Ago]
Imports System.Text.RegularExpressions

Module RegExSample
    Function CapText(ByVal m As Match) As String
        ' Get the matched string.
        Dim x As String = m.ToString()
        ' If the first char is lower case...
        If Char.IsLower(x.Chars(0)) Then
            ' Capitalize it.
            Return Char.ToUpper(x.Chars(0)) & x.Substring(1, x.Length - 1)
        End If
        Return x
    End Function

    Sub Main()
        Dim text As String = "four score and seven years ago"

        Console.WriteLine($"text=[{text}]")

        Dim rx As New Regex("\w+")

        Dim result As String = rx.Replace(text, AddressOf RegExSample.CapText)

        Console.WriteLine($"result=[{result}]")
    End Sub
End Module
' The example displays the following output:
'       text=[four score and seven years ago]
'       result=[Four Score And Seven Years Ago]

備註

Regex.Replace(String, MatchEvaluator)如果下列任一條件成立,方法就適合取代正則運算式比對:

  • 取代字串無法立即由正則運算式取代模式指定。

  • 取代字串會產生比對字串上完成的一些處理。

  • 取代字串會產生條件式處理。

方法相當於呼叫 方法, Regex.Matches(String) 並將傳 MatchCollection 回集合中的每個物件傳遞 Matchevaluator 委派。

正則運算式是由目前 Regex 物件的建構函式所定義的模式。

參數 evaluator 是您定義之自訂方法的委派,而且會檢查每個相符專案。 自訂方法必須具有下列簽章,才能符合 MatchEvaluator 委派。

public string MatchEvaluatorMethod(Match match)
Public Function MatchEvaluatorMethod(match As Match) As String

您的自訂方法會傳回字串,以取代相符的輸入。

如果取代作業的執行時間超出 RegexMatchTimeoutException 建構函式所指定的逾時間隔,就會擲回 Regex.Regex(String, RegexOptions, TimeSpan) 例外狀況。 呼叫建構函式時若未設定逾時間隔,則如果作業超過為建立 Regex 物件的應用程式定義域設定的任何逾時值,就會擲回例外狀況。 如果在 Regex 建構函式呼叫或應用程式定義域的屬性中未定義任何逾時,或逾時值是 Regex.InfiniteMatchTimeout,則不擲回任何例外狀況

因為方法在沒有相符專案時傳回 input 不變,所以您可以使用 Object.ReferenceEquals 方法來判斷方法是否已對輸入字串進行任何取代。

另請參閱

適用於

Replace(String, MatchEvaluator, Int32)

在指定的輸入字串中,使用 MatchEvaluator 委派所傳回的字串來取代符合規則運算式模式的指定最大字串數目。

public:
 System::String ^ Replace(System::String ^ input, System::Text::RegularExpressions::MatchEvaluator ^ evaluator, int count);
public string Replace (string input, System.Text.RegularExpressions.MatchEvaluator evaluator, int count);
member this.Replace : string * System.Text.RegularExpressions.MatchEvaluator * int -> string
Public Function Replace (input As String, evaluator As MatchEvaluator, count As Integer) As String

參數

input
String

用來搜尋比對的字串。

evaluator
MatchEvaluator

檢查每個符合項目並傳回原始符合字串或取代字串的自訂方法。

count
Int32

取代將發生的最多次數。

傳回

與輸入字串相同的新字串 (不同之處是取代字串會取代每一個相符的字串)。 如果規則運算式模式在目前執行個體中沒有符合項目,方法會傳回未變更的目前執行個體。

例外狀況

inputevaluatornull

發生逾時。 如需逾時的詳細資訊,請參閱<備註>一節。

範例

下列範例會使用正則運算式刻意拼錯清單中的一半字。 它會使用正則運算式 \w*(ie|ei)\w* 來比對包含 「ie」 或 「ei」 字元的字組。 它會將相符字的前半部傳遞至 ReverseLetter 方法,接著會使用 Replace(String, String, String, RegexOptions) 方法來反轉相符字串中的 「i」 和 「e」。 其餘單字保持不變。

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = "deceive relieve achieve belief fierce receive";
      string pattern = @"\w*(ie|ei)\w*";
      Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);
      Console.WriteLine("Original string: " + input);
      
      string result = rgx.Replace(input, new MatchEvaluator(Example.ReverseLetter), 
                                  input.Split(' ').Length / 2);
      Console.WriteLine("Returned string: " + result);
   }

   static string ReverseLetter(Match match)
   {
      return Regex.Replace(match.Value, "([ie])([ie])", "$2$1", 
                           RegexOptions.IgnoreCase);            
   }
}
// The example displays the following output:
//    Original string: deceive relieve achieve belief fierce receive
//    Returned string: decieve releive acheive belief fierce receive
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim input As String = "deceive relieve achieve belief fierce receive"
      Dim pattern As String = "\w*(ie|ei)\w*"
      Dim rgx As New Regex(pattern, RegexOptions.IgnoreCase)
      Console.WriteLine("Original string: " + input)
      
      Dim result As String = rgx.Replace(input, AddressOf ReverseLetter, 
                                           input.Split(" "c).Length \ 2)
      Console.WriteLine("Returned string: " + result)
   End Sub

   Public Function ReverseLetter(match As Match) As String
      Return Regex.Replace(match.Value, "([ie])([ie])", "$2$1", 
                           RegexOptions.IgnoreCase)            
   End Function
End Module
' The example displays the following output:
'    Original string: deceive relieve achieve belief fierce receive
'    Returned string: decieve releive acheive belief fierce receive

規則運算式 \w*(ie|ei)\w* 的定義如下表所示。

模式 描述
\w* 比對零個或多個文字字元。
(ie|ei) 比對 「ie」 或 「ei」。
\w* 比對零個或多個文字字元。

方法中的 ReverseLetter 正則運算式模式 ([ie])([ie]) 符合 diphthong 「ie」 或 「ei」 中的第一個 「i」 或 「e」,並將字母指派給第一個擷取群組。 它會比對第二個 「i」 或 「e」,並將字母指派給第二個擷取群組。 然後,使用取代模式 $2$1 呼叫 方法, Replace(String, String, String) 以反轉這兩個字元。

備註

Regex.Replace(String, MatchEvaluator, Int32)如果下列任一條件成立,方法就適合取代正則運算式比對:

  • 取代字串無法立即由正則運算式取代模式指定。

  • 取代字串會產生比對字串上完成的一些處理。

  • 取代字串會產生條件式處理。

方法相當於呼叫 Regex.Matches(String) 方法,並將傳 MatchCollection 回集合中的第一個 countMatch 物件傳遞至 evaluator 委派。

正則運算式是由目前 Regex 物件的建構函式所定義的模式。

參數 evaluator 是您定義之自訂方法的委派,而且會檢查每個相符專案。 自訂方法必須具有下列簽章,才能符合 MatchEvaluator 委派。

public string MatchEvaluatorMethod(Match match)
Public Function MatchEvaluatorMethod(match As Match) As String

您的自訂方法會傳回字串,以取代相符的輸入。

如果取代作業的執行時間超出 RegexMatchTimeoutException 建構函式所指定的逾時間隔,就會擲回 Regex.Regex(String, RegexOptions, TimeSpan) 例外狀況。 呼叫建構函式時若未設定逾時間隔,則如果作業超過為建立 Regex 物件的應用程式定義域設定的任何逾時值,就會擲回例外狀況。 如果在 Regex 建構函式呼叫或應用程式定義域的屬性中未定義任何逾時,或逾時值是 Regex.InfiniteMatchTimeout,則不擲回任何例外狀況

因為方法在沒有相符專案時傳回 input 不變,所以您可以使用 Object.ReferenceEquals 方法來判斷方法是否已對輸入字串進行任何取代。

另請參閱

適用於

Replace(String, String, MatchEvaluator)

在指定的輸入字串中,使用由 MatchEvaluator 委派所傳回的字串,取代所有與指定之規則運算式相符的字串。

public:
 static System::String ^ Replace(System::String ^ input, System::String ^ pattern, System::Text::RegularExpressions::MatchEvaluator ^ evaluator);
public static string Replace (string input, string pattern, System.Text.RegularExpressions.MatchEvaluator evaluator);
static member Replace : string * string * System.Text.RegularExpressions.MatchEvaluator -> string
Public Shared Function Replace (input As String, pattern As String, evaluator As MatchEvaluator) As String

參數

input
String

用來搜尋比對的字串。

pattern
String

要比對的規則運算式模式。

evaluator
MatchEvaluator

檢查每個符合項目並傳回原始符合字串或取代字串的自訂方法。

傳回

與輸入字串相同的新字串 (不同之處是取代字串會取代每一個相符的字串)。 如果在目前的執行個體中沒有符合 pattern 的項目,則方法傳回未變更的目前執行個體。

例外狀況

發生規則運算式剖析錯誤。

inputpatternevaluatornull

發生逾時。 如需逾時的詳細資訊,請參閱<備註>一節。

範例

下列範例會使用正則運算式從字串中擷取個別字組,然後使用 MatchEvaluator 委派來呼叫名為 WordScramble 的方法,以拼字中的個別字母。 若要這樣做, WordScramble 方法會建立陣列,其中包含比對中的字元。 它也會建立以隨機浮點數填入的平行陣列。 陣列會藉由呼叫 Array.Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>) 方法來排序,而且已排序的陣列會當做類別建構函式的 String 引數提供。 這個新建立的 WordScramble 字串接著會由 方法傳回。 正則運算式模式 \w+ 符合一或多個字字元;正則運算式引擎會繼續將字元新增至相符專案,直到遇到非單字字元,例如空白字元為止。

using System;
using System.Collections;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string words = "letter alphabetical missing lack release " + 
                     "penchant slack acryllic laundry cease";
      string pattern = @"\w+";                            
      MatchEvaluator evaluator = new MatchEvaluator(WordScrambler);
      Console.WriteLine("Original words:");
      Console.WriteLine(words);
      Console.WriteLine();
      Console.WriteLine("Scrambled words:");
      Console.WriteLine(Regex.Replace(words, pattern, evaluator));      
   }

   public static string WordScrambler(Match match)
   {
      int arraySize = match.Value.Length;
      // Define two arrays equal to the number of letters in the match.
      double[] keys = new double[arraySize];
      char[] letters = new char[arraySize];
      
      // Instantiate random number generator'
      Random rnd = new Random();
      
      for (int ctr = 0; ctr < match.Value.Length; ctr++)
      {
         // Populate the array of keys with random numbers.
         keys[ctr] = rnd.NextDouble();
         // Assign letter to array of letters.
         letters[ctr] = match.Value[ctr];
      }         
      Array.Sort(keys, letters, 0, arraySize, Comparer.Default);      
      return new String(letters);
   }
}
// The example displays output similar to the following:
//    Original words:
//    letter alphabetical missing lack release penchant slack acryllic laundry cease
//    
//    Scrambled words:
//    elrtte iaeabatlpchl igmnssi lcka aerslee hnpatnce ksacl lialcryc dylruna ecase
Imports System.Collections
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim words As String = "letter alphabetical missing lack release " + _
                            "penchant slack acryllic laundry cease"
      Dim pattern As String = "\w+"                            
      Dim evaluator As MatchEvaluator = AddressOf WordScrambler
      Console.WriteLine("Original words:")
      Console.WriteLine(words)
      Console.WriteLine("Scrambled words:")
      Console.WriteLine(Regex.Replace(words, pattern, evaluator))      
   End Sub
   
   Public Function WordScrambler(match As Match) As String
      Dim arraySize As Integer = match.Value.Length - 1
      ' Define two arrays equal to the number of letters in the match.
      Dim keys(arraySize) As Double
      Dim letters(arraySize) As Char
      
      ' Instantiate random number generator'
      Dim rnd As New Random()
      
      For ctr As Integer = 0 To match.Value.Length - 1
         ' Populate the array of keys with random numbers.
         keys(ctr) = rnd.NextDouble()
         ' Assign letter to array of letters.
         letters(ctr) = match.Value.Chars(ctr)
      Next         
      Array.Sort(keys, letters, 0, arraySize, Comparer.Default)      
      Return New String(letters)
   End Function
End Module
' The example displays output similar to the following:
'    Original words:
'    letter alphabetical missing lack release penchant slack acryllic laundry cease
'    
'    Scrambled words:
'    elrtte iaeabatlpchl igmnssi lcka aerslee hnpatnce ksacl lialcryc dylruna ecase

備註

Regex.Replace(String, String, MatchEvaluator)如果下列任一條件成立,方法就適合取代正則運算式比對:

  • 取代字串無法立即由正則運算式取代模式指定。

  • 取代字串會產生比對字串上完成的一些處理。

  • 取代字串會產生條件式處理。

方法相當於呼叫 方法, Regex.Matches(String, String) 並將傳 MatchCollection 回集合中的每個物件傳遞 Matchevaluator 委派。

pattern 參數包含規則運算式語言項目,以透過符號描述要比對的字串。 如需正則運算式的詳細資訊,請參閱 .NET 正則運算式正則運算式語言 - 快速參考

參數 evaluator 是您定義之自訂方法的委派,而且會檢查每個相符專案。 自訂方法必須具有下列簽章,才能符合 MatchEvaluator 委派。

public string MatchEvaluatorMethod(Match match)
Public Function MatchEvaluatorMethod(match As Match) As String

您的自訂方法會傳回字串,以取代相符的輸入。

如果取代作業的執行時間超出為呼叫方法的應用程式定義域指定的逾時間隔,就會擲回 RegexMatchTimeoutException 例外狀況。 如果在應用程式定義域的屬性中未定義任何逾時,或逾時值是 Regex.InfiniteMatchTimeout,則不擲回任何例外狀況。

因為如果沒有相符專案,方法會傳回 input 未變更,所以您可以使用 Object.ReferenceEquals 方法來判斷方法是否已對輸入字串進行任何取代。

給呼叫者的注意事項

這個方法的逾時間隔等於呼叫這個方法的應用程式定義域的預設逾時值。 如果未針對應用程式定義域定義逾時值,則使用值 InfiniteMatchTimeout,使方法不會逾時。 評估及取代模式比對的建議靜態方法為 Replace(String, String, MatchEvaluator, RegexOptions, TimeSpan) ,可讓您設定逾時間隔。

另請參閱

適用於

Replace(String, String, Int32)

在指定的輸入字串中,使用指定的取代字串來取代符合規則運算式模式的指定最大字串數目。

public:
 System::String ^ Replace(System::String ^ input, System::String ^ replacement, int count);
public string Replace (string input, string replacement, int count);
member this.Replace : string * string * int -> string
Public Function Replace (input As String, replacement As String, count As Integer) As String

參數

input
String

用來搜尋比對的字串。

replacement
String

取代字串。

count
Int32

取代作業可以發生的最大次數。

傳回

與輸入字串相同的新字串 (不同之處是取代字串會取代每一個相符的字串)。 如果規則運算式模式在目前執行個體中沒有符合項目,方法會傳回未變更的目前執行個體。

例外狀況

inputreplacementnull

發生逾時。 如需逾時的詳細資訊,請參閱<備註>一節。

範例

下列範例會將重複字元的前五個出現專案取代為單一字元。 正則運算式模式 (\w)\1 會比對單一字元的連續出現次數,並將第一個出現專案指派給第一個擷取群組。 取代模式 $1 會將整個相符專案取代為第一個擷取的群組。

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string str = "aabccdeefgghiijkklmm";
      string pattern = "(\\w)\\1"; 
      string replacement = "$1"; 
      Regex rgx = new Regex(pattern);

      string result = rgx.Replace(str, replacement, 5);
      Console.WriteLine("Original String:    '{0}'", str);
      Console.WriteLine("Replacement String: '{0}'", result); 
   }
}
// The example displays the following output:
//       Original String:    'aabccdeefgghiijkklmm'
//       Replacement String: 'abcdefghijkklmm'
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim str As String = "aabccdeefgghiijkklmm"
      Dim pattern As String = "(\w)\1" 
      Dim replacement As String = "$1" 
      Dim rgx As New Regex(pattern)

      Dim result As String = rgx.Replace(str, replacement, 5)
      Console.WriteLine("Original String:    '{0}'", str)
      Console.WriteLine("Replacement String: '{0}'", result)                             
   End Sub
End Module
' The example displays the following output:
'       Original String:    'aabccdeefgghiijkklmm'
'       Replacement String: 'abcdefghijkklmm'

備註

搜尋相符專案會從字串開頭 input 開始。 正則運算式是由目前 Regex 物件的建構函式所定義的模式。 如果 count 為負數,則取代會繼續到字串結尾。 如果 count 超過相符專案的數目,則會取代所有相符專案。

參數 replacement 會指定要取代 中 input 第一個 count 相符專案的字串。 replacement 可以包含常值文字和 替代的任何組合。 例如,取代模式 a*${test}b 會插入字串 「a*」,後面接著擷取群組比對的子字串 test ,如果有的話,後面接著字串 「b」。 * 字元在取代模式中無法辨識為中繼字元。

注意

替代是替代模式中唯一可辨識的正則運算式語言專案。 所有其他正則運算式語言專案,包括 字元逸出,只能在正則運算式模式中允許,而且無法在取代模式中辨識。

如果取代作業的執行時間超出 RegexMatchTimeoutException 建構函式所指定的逾時間隔,就會擲回 Regex.Regex(String, RegexOptions, TimeSpan) 例外狀況。 呼叫建構函式時若未設定逾時間隔,則如果作業超過為建立 Regex 物件的應用程式定義域設定的任何逾時值,就會擲回例外狀況。 如果在 Regex 建構函式呼叫或應用程式定義域的屬性中未定義任何逾時,或逾時值是 Regex.InfiniteMatchTimeout,則不擲回任何例外狀況

因為如果沒有相符專案,方法會傳回 input 未變更,所以您可以使用 Object.ReferenceEquals 方法來判斷方法是否已對輸入字串進行任何取代。

另請參閱

適用於

Replace(String, String)

在指定的輸入字串中,使用指定的取代字串來取代符合規則運算式模式的所有字串。

public:
 System::String ^ Replace(System::String ^ input, System::String ^ replacement);
public string Replace (string input, string replacement);
member this.Replace : string * string -> string
Public Function Replace (input As String, replacement As String) As String

參數

input
String

用來搜尋比對的字串。

replacement
String

取代字串。

傳回

與輸入字串相同的新字串 (不同之處是取代字串會取代每一個相符的字串)。 如果規則運算式模式在目前執行個體中沒有符合項目,方法會傳回未變更的目前執行個體。

例外狀況

inputreplacementnull

發生逾時。 如需逾時的詳細資訊,請參閱<備註>一節。

範例

下列範例會定義符合一或多個空白字元的正則運算式 \s+ 。 取代字串 「 」,會以單一空白字元取代它們。

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = "This is   text with   far  too   much   " + 
                     "white space.";
      string pattern = "\\s+";
      string replacement = " ";
      Regex rgx = new Regex(pattern);
      string result = rgx.Replace(input, replacement);
      
      Console.WriteLine("Original String: {0}", input);
      Console.WriteLine("Replacement String: {0}", result);                             
   }
}
// The example displays the following output:
//       Original String: This is   text with   far  too   much   white space.
//       Replacement String: This is text with far too much white space.
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim input As String = "This is   text with   far  too   much   " + _
                            "white space."
      Dim pattern As String = "\s+"
      Dim replacement As String = " "
      Dim rgx As New Regex(pattern)
      Dim result As String = rgx.Replace(input, replacement)
      
      Console.WriteLine("Original String: {0}", input)
      Console.WriteLine("Replacement String: {0}", result)                             
   End Sub
End Module
' The example displays the following output:
'          Original String: This is   text with   far  too   much   white space.
'          Replacement String: This is text with far too much white space.

下列範例會定義正則運算式 (\p{Sc}\s?)?(\d+\.?((?<=\.)\d+)?)(?(1)|\s?\p{Sc})? 、 和取代模式 $2 ,它會從數值中移除前置或尾端貨幣符號。

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string pattern =  @"(\p{Sc}\s?)?(\d+\.?((?<=\.)\d+)?)(?(1)|\s?\p{Sc})?";
      string input = "$17.43  €2 16.33  £0.98  0.43   £43   12€  17";
      string replacement = "$2";
      Regex rgx = new Regex(pattern);
      string result = rgx.Replace(input, replacement);

      Console.WriteLine("Original String:    '{0}'", input);
      Console.WriteLine("Replacement String: '{0}'", result);                             
   }
}
// The example displays the following output:
//       Original String:    '$17.43  €2 16.33  £0.98  0.43   £43   12€  17'
//       Replacement String: '17.43  2 16.33  0.98  0.43   43   12  17'
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim pattern As String =  "(\p{Sc}\s?)?(\d+\.?((?<=\.)\d+)?)(?(1)|\s?\p{Sc})?"
      Dim input As String = "$17.43  €2 16.33  £0.98  0.43   £43   12€  17"
      Dim replacement As String = "$2"
      Dim rgx As New Regex(pattern)
      Dim result As String = rgx.Replace(input, replacement)

      Console.WriteLine("Original String:    '{0}'", input)
      Console.WriteLine("Replacement String: '{0}'", result)                             
   End Sub
End Module
' The example displays the following output:
'       Original String:    '$17.43  €2 16.33  £0.98  0.43   £43   12€  17'
'       Replacement String: '17.43  2 16.33  0.98  0.43   43   12  17'

規則運算式的解譯方式如下表所示。

模式 描述
\p{Sc} 比對貨幣符號。 {Sc} 表示任何屬於 Unicode 符號、貨幣類別目錄成員的字元。
\s? 比對零個或一個空白字元。
(\p{Sc}\s?)? 比對零或一次出現貨幣符號的組合,後面接著零或一個空白字元。 這是第一個擷取群組。
\d+ 比對一個或多個十進位數字。
\.? 比對零次或一次出現的句點, (做為小數分隔符號) 。
((?<=\.)\d+)? 如果句號是前一個字元,請比對一或多個十進位數。 此模式可以比對零或一次。
(\d+\.?((?<=\.)\d+)?) 比對一或多個十進位數的模式,後面接著選擇性句點和其他十進位數。 這是第二個擷取群組。 方法的 Replace(String, String) 呼叫會以這個擷取群組的值取代整個相符專案。
(?(1)|\s?\p{Sc})? 如果第一個擷取的群組存在,請比對空字串。 否則,請比對零或一個空白字元,後面接著貨幣符號。

備註

搜尋相符專案會從字串開頭 input 開始。 正則運算式是由目前 Regex 物件的建構函式所定義的模式。

參數 replacement 會指定要取代 中每個相符項的 input 字串。 replacement 可以包含常值文字和 替代的任何組合。 例如,取代模式 a*${test}b 會插入字串 「a*」,後面接著擷取群組比對的子字串 test ,如果有的話,後面接著字串 「b」。 * 字元在取代模式中無法辨識為中繼字元。

注意

替代是替代模式中唯一可辨識的正則運算式語言專案。 所有其他正則運算式語言專案,包括 字元逸出,只能在正則運算式模式中允許,而且無法在取代模式中辨識。

如果取代作業的執行時間超出 RegexMatchTimeoutException 建構函式所指定的逾時間隔,就會擲回 Regex.Regex(String, RegexOptions, TimeSpan) 例外狀況。 呼叫建構函式時若未設定逾時間隔,則如果作業超過為建立 Regex 物件的應用程式定義域設定的任何逾時值,就會擲回例外狀況。 如果在 Regex 建構函式呼叫或應用程式定義域的屬性中未定義任何逾時,或逾時值是 Regex.InfiniteMatchTimeout,則不擲回任何例外狀況

因為如果沒有相符專案,方法會傳回 input 未變更,所以您可以使用 Object.ReferenceEquals 方法來判斷方法是否已對輸入字串進行任何取代。

另請參閱

適用於

Replace(String, String, Int32, Int32)

在指定的輸入子字串中,使用指定的取代字串來取代符合規則運算式模式的指定最大字串數目。

public:
 System::String ^ Replace(System::String ^ input, System::String ^ replacement, int count, int startat);
public string Replace (string input, string replacement, int count, int startat);
member this.Replace : string * string * int * int -> string
Public Function Replace (input As String, replacement As String, count As Integer, startat As Integer) As String

參數

input
String

用來搜尋比對的字串。

replacement
String

取代字串。

count
Int32

取代可以發生的最多次數。

startat
Int32

在輸入字串中開始搜尋的字元位置。

傳回

與輸入字串相同的新字串 (不同之處是取代字串會取代每一個相符的字串)。 如果規則運算式模式在目前執行個體中沒有符合項目,方法會傳回未變更的目前執行個體。

例外狀況

inputreplacementnull

startat 小於零或大於 input 的長度。

發生逾時。 如需逾時的詳細資訊,請參閱<備註>一節。

範例

下列範例會將字串的第一行全都加空格。 它會定義符合文字行的正則運算式模式 ^.*$ 、呼叫 Match(String) 方法來比對字串的第一行,並使用 Match.IndexMatch.Count 屬性來判斷第二行的起始位置。

using System;
using System.Text.RegularExpressions;

public class Example
{
   public static void Main()
   {
      string input = "Instantiating a New Type\n" +
                     "Generally, there are two ways that an\n" + 
                     "instance of a class or structure can\n" +
                     "be instantiated. ";
      string pattern = "^.*$";
      string replacement = "\n$&";
      Regex rgx = new Regex(pattern, RegexOptions.Multiline);
      string result = String.Empty; 
      
      Match match = rgx.Match(input);
      // Double space all but the first line.
      if (match.Success) 
         result = rgx.Replace(input, replacement, -1, match.Index + match.Length + 1);

      Console.WriteLine(result);                     
   }
}
// The example displays the following output:
//       Instantiating a New Type
//       
//       Generally, there are two ways that an
//       
//       instance of a class or structure can
//       
//       be instntiated.
Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim input As String = "Instantiating a New Type" + vbCrLf + _
                            "Generally, there are two ways that an" + vbCrLf + _
                            "instance of a class or structure can" + vbCrLf + _
                            "be instantiated. "
      Dim pattern As String = "^.*$"
      Dim replacement As String = vbCrLf + "$&"
      Dim rgx As New Regex(pattern, RegexOptions.Multiline)
      Dim result As String = String.Empty 
      
      Dim match As Match = rgx.Match(input)
      ' Double space all but the first line.
      If match.Success Then 
         result = rgx.Replace(input, replacement, -1, match.Index + match.Length + 1)
      End If
      Console.WriteLine(result)                      
   End Sub
End Module
' The example displays the following output:
'       Instantiating a New Type
'       
'       Generally, there are two ways that an
'       
'       instance of a class or structure can
'       
'       be instntiated.

規則運算式模式 ^.*$ 的定義如下表所示。

模式 描述
^ 比對行的開頭。 (請注意, Regex 物件是使用 RegexOptions.Multiline 選項具現化;否則,這個字元類別只會符合輸入字串的開頭。)
.* 比對任何字元零或多次。
$ 比對行尾。 (請注意, Regex 物件是使用 RegexOptions.Multiline 選項具現化;否則,這個字元類別只會符合輸入字串的開頭。)

Visual Basic 中的取代字串 (vbCrLf + "$&""\n$&" 在 C#) 會在相符字串之前新增一行。 請注意, \n 在 C# 範例中,C# 編譯器會解譯為分行符號;它不代表正則運算式字元逸出。

備註

搜尋相符專案會在 參數所 startat 指定位置的字串中 input 開始。 正則運算式是由目前 Regex 物件的建構函式所定義的模式。 如果 count 為負數,則取代會繼續到字串的結尾。 如果 count 超過相符專案的數目,則會取代所有相符專案。

如需 的詳細資訊 startat ,請參閱 的一 Match(String, Int32) 節。

參數 replacement 會指定要取代 中每個相符項的 input 字串。 replacement 可以包含常值文字和 替代的任何組合。 例如,取代模式 a*${test}b 會插入字串 「a*」,後面接著與擷取群組相符 test 的子字串,如果有的話,後面接著字串 「b」。 * 字元在取代模式中無法辨識為中繼字元。

注意

替代是取代模式中唯一辨識的正則運算式語言專案。 所有其他正則運算式語言專案,包括 字元逸出,只能在正則運算式模式中允許,而且在取代模式中無法辨識。

如果取代作業的執行時間超出 RegexMatchTimeoutException 建構函式所指定的逾時間隔,就會擲回 Regex.Regex(String, RegexOptions, TimeSpan) 例外狀況。 呼叫建構函式時若未設定逾時間隔,則如果作業超過為建立 Regex 物件的應用程式定義域設定的任何逾時值,就會擲回例外狀況。 如果在 Regex 建構函式呼叫或應用程式定義域的屬性中未定義任何逾時,或逾時值是 Regex.InfiniteMatchTimeout,則不擲回任何例外狀況

因為方法在沒有相符專案時傳回 input 不變,所以您可以使用 Object.ReferenceEquals 方法來判斷方法是否已對輸入字串進行任何取代。

另請參閱

適用於