共用方式為


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)

來源:
Regex.Replace.cs
來源:
Regex.Replace.cs
來源:
Regex.Replace.cs

在指定的輸入子字串中,以 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

您的自定義方法會傳回取代相符輸入的字串。

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

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

另請參閱

適用於

Replace(String, String, String)

來源:
Regex.Replace.cs
來源:
Regex.Replace.cs
來源:
Regex.Replace.cs

在指定的輸入字串中,以指定的取代字串取代符合指定正規表示式的所有字串。

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)

來源:
Regex.Replace.cs
來源:
Regex.Replace.cs
來源:
Regex.Replace.cs

在指定的輸入字串中,將符合指定正則表示式的所有子字串取代為 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 集合中的每個 Match 對象傳遞至 evaluator 委派。

pattern 參數是由正則表達式語言專案所組成,這些元素會以符號方式描述要比對的字串。 如需正規表示式的詳細資訊,請參閱 .NET 正則表示式正則表示式語言 - 快速參考

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

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

您的自定義方法會傳回取代相符輸入的字串。

如果您為 options 參數指定 RightToLeft,搜尋相符專案會從輸入字串的結尾開始,並向左移動;否則,搜尋會從輸入字串的開頭開始,然後向右移動。

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

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

給呼叫者的注意事項

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

  • 正則表達式所處理的輸入衍生自已知且受信任的來源,或包含靜態文字時。 這會排除使用者動態輸入的文字。

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

  • 當正則表達式模式不包含任何已知在處理接近相符專案時造成過度回溯的語言元素。

另請參閱

適用於

Replace(String, String, MatchEvaluator, RegexOptions)

來源:
Regex.Replace.cs
來源:
Regex.Replace.cs
來源:
Regex.Replace.cs

在指定的輸入字串中,將符合指定正則表示式的所有字串取代為 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 集合中的每個 Match 對象傳遞至 evaluator 委派。

pattern 參數是由正則表達式語言專案所組成,這些元素會以符號方式描述要比對的字串。 如需正規表示式的詳細資訊,請參閱 .NET 正則表示式正則表示式語言 - 快速參考

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

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

您的自定義方法會傳回取代相符輸入的字串。

如果您為 options 參數指定 RightToLeft,搜尋相符專案會從輸入字串的結尾開始,並向左移動;否則,搜尋會從輸入字串的開頭開始,然後向右移動。

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

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

另請參閱

適用於

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

來源:
Regex.Replace.cs
來源:
Regex.Replace.cs
來源:
Regex.Replace.cs

在指定的輸入字串中,以指定的取代字串取代符合指定正規表示式的所有字串。 其他參數會指定修改比對作業的選項,如果找不到相符專案,則會指定超時時間間隔。

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 正則表示式正則表示式語言 - 快速參考。 如果您為 options 參數指定 RightToLeft,搜尋相符專案會從輸入字串的結尾開始,並向左移動;否則,搜尋會從輸入字串的開頭開始,然後向右移動。

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

注意

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

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

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

給呼叫者的注意事項

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

  • 正則表達式所處理的輸入衍生自已知且受信任的來源,或包含靜態文字時。 這會排除使用者動態輸入的文字。

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

  • 當正則表達式模式不包含任何已知在處理接近相符專案時造成過度回溯的語言元素。

另請參閱

適用於

Replace(String, String, String, RegexOptions)

來源:
Regex.Replace.cs
來源:
Regex.Replace.cs
來源:
Regex.Replace.cs

在指定的輸入字串中,以指定的取代字串取代符合指定正規表示式的所有字串。 指定的選項會修改比對作業。

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 正則表示式正則表示式語言 - 快速參考。 如果您為 options 參數指定 RightToLeft,搜尋相符專案會從輸入字串的結尾開始,並向左移動;否則,搜尋會從輸入字串的開頭開始,然後向右移動。

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)

來源:
Regex.Replace.cs
來源:
Regex.Replace.cs
來源:
Regex.Replace.cs

在指定的輸入字串中,將符合指定正則表示式的所有字串取代為 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 集合中的每個 Match 對象傳遞至 evaluator 委派。

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

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

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

您的自定義方法會傳回取代相符輸入的字串。

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

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

另請參閱

適用於

Replace(String, MatchEvaluator, Int32)

來源:
Regex.Replace.cs
來源:
Regex.Replace.cs
來源:
Regex.Replace.cs

在指定的輸入字串中,使用 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」,並將字母指派給第二個擷取群組。 然後,使用取代模式呼叫 Replace(String, String, String) 方法,$2$1來反轉這兩個字元。

備註

如果下列任一條件成立,則 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

您的自定義方法會傳回取代相符輸入的字串。

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

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

另請參閱

適用於

Replace(String, String, MatchEvaluator)

來源:
Regex.Replace.cs
來源:
Regex.Replace.cs
來源:
Regex.Replace.cs

在指定的輸入字串中,將符合指定正則表示式的所有字串取代為 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 集合中的每個 Match 對象傳遞至 evaluator 委派。

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)

來源:
Regex.Replace.cs
來源:
Regex.Replace.cs
來源:
Regex.Replace.cs

在指定的輸入字串中,以指定的取代字串取代符合正則表示式模式的指定最大字串數目。

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”。 * 字元在取代模式內無法辨識為中繼字元。

注意

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

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

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

另請參閱

適用於

Replace(String, String)

來源:
Regex.Replace.cs
來源:
Regex.Replace.cs
來源:
Regex.Replace.cs

在指定的輸入字串中,以指定的取代字串取代符合正則表示式模式的所有字串。

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”。 * 字元在取代模式內無法辨識為中繼字元。

注意

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

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

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

另請參閱

適用於

Replace(String, String, Int32, Int32)

來源:
Regex.Replace.cs
來源:
Regex.Replace.cs
來源:
Regex.Replace.cs

在指定的輸入子字串中,以指定的取代字串取代符合正則表示式模式的指定最大字串數目。

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 + "$&" C# "\n$&") 會在相符字串之前新增一行。 請注意,C# 範例中的 \n 會解譯為 C# 編譯程式的新行字元;它不代表正則表達式字元逸出。

備註

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

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

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

注意

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

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

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

另請參閱

適用於