Regex.Replace Regex.Replace Regex.Replace Regex.Replace Method

定義

在指定的輸入字串中,使用指定的取代字串來取代符合規則運算式模式的字串。In a specified input string, replaces strings that match a regular expression pattern with a specified replacement string.

多載

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

在指定的輸入字串中,使用 MatchEvaluator 委派所傳回的字串,取代所有與指定之規則運算式相符的子字串。In a specified input string, replaces all substrings that match a specified regular expression with a string returned by a MatchEvaluator delegate. 如果沒有找到相符項目,其他參數會指定修改比對作業的選項和逾時間隔。Additional parameters specify options that modify the matching operation and a time-out interval if no match is found.

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

在指定的輸入字串中,使用指定的取代字串來取代符合指定之規則運算式的所有字串。In a specified input string, replaces all strings that match a specified regular expression with a specified replacement string. 如果沒有找到相符項目,其他參數會指定修改比對作業的選項和逾時間隔。Additional parameters specify options that modify the matching operation and a time-out interval if no match is found.

Replace(String, MatchEvaluator, Int32, Int32) Replace(String, MatchEvaluator, Int32, Int32) Replace(String, MatchEvaluator, Int32, Int32) Replace(String, MatchEvaluator, Int32, Int32)

在指定的輸入子字串中,使用 MatchEvaluator 委派所傳回的字串來取代符合規則運算式模式的指定最大字串數目。In a specified input substring, replaces a specified maximum number of strings that match a regular expression pattern with a string returned by a MatchEvaluator delegate.

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

在指定的輸入字串中,使用由 MatchEvaluator 委派所傳回的字串,取代所有與指定之規則運算式相符的字串。In a specified input string, replaces all strings that match a specified regular expression with a string returned by a MatchEvaluator delegate. 指定的選項會修改符合的作業。Specified options modify the matching operation.

Replace(String, String, Int32, Int32) Replace(String, String, Int32, Int32) Replace(String, String, Int32, Int32) Replace(String, String, Int32, Int32)

在指定的輸入子字串中,使用指定的取代字串來取代符合規則運算式模式的指定最大字串數目。In a specified input substring, replaces a specified maximum number of strings that match a regular expression pattern with a specified replacement string.

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

在指定的輸入字串中,使用指定的取代字串來取代符合指定之規則運算式的所有字串。In a specified input string, replaces all strings that match a specified regular expression with a specified replacement string. 指定的選項會修改符合的作業。Specified options modify the matching operation.

Replace(String, String, MatchEvaluator) Replace(String, String, MatchEvaluator) Replace(String, String, MatchEvaluator) Replace(String, String, MatchEvaluator)

在指定的輸入字串中,使用由 MatchEvaluator 委派所傳回的字串,取代所有與指定之規則運算式相符的字串。In a specified input string, replaces all strings that match a specified regular expression with a string returned by a MatchEvaluator delegate.

Replace(String, String, String) Replace(String, String, String) Replace(String, String, String) Replace(String, String, String)

在指定的輸入字串中,使用指定的取代字串來取代符合指定之規則運算式的所有字串。In a specified input string, replaces all strings that match a specified regular expression with a specified replacement string.

Replace(String, String, Int32) Replace(String, String, Int32) Replace(String, String, Int32) Replace(String, String, Int32)

在指定的輸入字串中,使用指定的取代字串來取代符合規則運算式模式的指定最大字串數目。In a specified input string, replaces a specified maximum number of strings that match a regular expression pattern with a specified replacement string.

Replace(String, MatchEvaluator) Replace(String, MatchEvaluator) Replace(String, MatchEvaluator) Replace(String, MatchEvaluator)

在指定的輸入字串中,使用由 MatchEvaluator 委派所傳回的字串,取代所有與指定之規則運算式相符的字串。In a specified input string, replaces all strings that match a specified regular expression with a string returned by a MatchEvaluator delegate.

Replace(String, String) Replace(String, String) Replace(String, String) Replace(String, String)

在指定的輸入字串中,使用指定的取代字串來取代符合規則運算式模式的所有字串。In a specified input string, replaces all strings that match a regular expression pattern with a specified replacement string.

Replace(String, MatchEvaluator, Int32) Replace(String, MatchEvaluator, Int32) Replace(String, MatchEvaluator, Int32) Replace(String, MatchEvaluator, Int32)

在指定的輸入字串中,使用 MatchEvaluator 委派所傳回的字串來取代符合規則運算式模式的指定最大字串數目。In a specified input string, replaces a specified maximum number of strings that match a regular expression pattern with a string returned by a MatchEvaluator delegate.

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

在指定的輸入字串中,使用 MatchEvaluator 委派所傳回的字串,取代所有與指定之規則運算式相符的子字串。In a specified input string, replaces all substrings that match a specified regular expression with a string returned by a MatchEvaluator delegate. 如果沒有找到相符項目,其他參數會指定修改比對作業的選項和逾時間隔。Additional parameters specify options that modify the matching operation and a time-out interval if no match is found.

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 String String String

用來搜尋比對的字串。The string to search for a match.

pattern
String String String String

要比對的規則運算式模式。The regular expression pattern to match.

evaluator
MatchEvaluator MatchEvaluator MatchEvaluator MatchEvaluator

檢查每個符合項目並傳回原始符合字串或取代字串的自訂方法。A custom method that examines each match and returns either the original matched string or a replacement string.

options
RegexOptions RegexOptions RegexOptions RegexOptions

列舉值的位元組合,提供用於比對的選項。A bitwise combination of enumeration values that provide options for matching.

matchTimeout
TimeSpan TimeSpan TimeSpan TimeSpan

逾時間隔,若要表示此方法不應逾時則為 InfiniteMatchTimeoutA time-out interval, or InfiniteMatchTimeout to indicate that the method should not time out.

傳回

與輸入字串相同的新字串 (不同之處是取代字串會取代每一個相符的字串)。A new string that is identical to the input string, except that the replacement string takes the place of each matched string. 如果在目前的執行個體中沒有符合 pattern 的項目,則方法傳回未變更的目前執行個體。If pattern is not matched in the current instance, the method returns the current instance unchanged.

例外狀況

發生規則運算式剖析錯誤。A regular expression parsing error occurred.

inputpatternevaluatornullinput, pattern, or evaluator is null.

options 不是 RegexOptions 值的有效位元組合。options is not a valid bitwise combination of RegexOptions values.

-或--or- matchTimeout 為負數、零或約大於 24 天。matchTimeout is negative, zero, or greater than approximately 24 days.

發生逾時。A time-out occurred. 如需逾時的詳細資訊,請參閱<備註>一節。For more information about time-outs, see the Remarks section.

範例

下列範例會使用正則運算式, 將字串中的個別單字解壓縮, 然後使用MatchEvaluator委派呼叫名為WordScramble的方法, 以將單字中的個別字母進行編碼。The following example uses a regular expression to extract the individual words from a string, and then uses a MatchEvaluator delegate to call a method named WordScramble that scrambles the individual letters in the word. 若要這麼做, WordScramble方法會建立陣列, 其中包含相符的字元。To do this, the WordScramble method creates an array that contains the characters in the match. 它也會建立以隨機浮點數填入的平行陣列。It also creates a parallel array that it populates with random floating-point numbers. 陣列會藉由呼叫Array.Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>)方法來排序, 而且已排序的陣列會當做引數提供給類別的String函式。The arrays are sorted by calling the Array.Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>) method, and the sorted array is provided as an argument to a String class constructor. 這個新建立的WordScramble字串接著會由方法傳回。This newly created string is then returned by the WordScramble method. 正則運算式模式\w+會比對一或多個文字字元, 正則運算式引擎會繼續將字元加入至比對, 直到遇到非文字字元 (如空白字元) 為止。The regular expression pattern \w+ matches one or more word characters; the regular expression engine will continue to add characters to the match until it encounters a non-word character, such as a white-space character. Replace(String, String, MatchEvaluator, RegexOptions)方法的呼叫RegexOptions.IgnorePatternWhitespace包含選項, 因此正則運算式引擎會忽略正則運算式模式\w+ # Matches all the characters in a word.中的批註。The call to the Replace(String, String, MatchEvaluator, RegexOptions) method includes the RegexOptions.IgnorePatternWhitespace option so that the comment in the regular expression pattern \w+ # Matches all the characters in a word. is ignored by the regular expression engine.

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)下列任一條件成立時, 方法適用于取代正則運算式相符:The Regex.Replace(String, String, MatchEvaluator, RegexOptions) method is useful for replacing a regular expression match if any of the following conditions is true:

  • 如果取代字串無法輕易地由正則運算式取代模式指定, 則為。If the replacement string cannot readily be specified by a regular expression replacement pattern.

  • 如果取代字串的結果來自于相符字串上執行的某些處理, 則為。If the replacement string results from some processing performed on the matched string.

  • 如果來自條件式處理的取代字串結果, 則為。If the replacement string results from conditional processing.

方法相當Regex.Matches(String, String, RegexOptions)于呼叫方法, 並將傳回MatchCollection之集合Matchevaluator的每個物件傳遞給委派。The method is equivalent to calling the Regex.Matches(String, String, RegexOptions) method and passing each Match object in the returned MatchCollection collection to the evaluator delegate.

pattern 參數包含規則運算式語言項目,以透過符號描述要比對的字串。The pattern parameter consists of regular expression language elements that symbolically describe the string to match. 如需正則運算式的詳細資訊, 請參閱.NET Framework 正則運算式正則運算式語言-快速參考For more information about regular expressions, see .NET Framework Regular Expressions and Regular Expression Language - Quick Reference.

evaluator參數是您定義之自訂方法的委派, 它會檢查每個相符的。The evaluator parameter is the delegate for a custom method that you define and that examines each match. 自訂方法必須具有下列簽章, 才能符合MatchEvaluator委派。The custom method must have the following signature to match the MatchEvaluator delegate.

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

您的自訂方法會傳回一個字串, 取代相符的輸入。Your custom method returns a string that replaces the matched input.

如果為 RightToLeft 參數指定 options,搜尋符合項目會從輸入字串結尾開始向左移動,否則,搜尋會從輸入字串開頭開始向右移動。If you specify RightToLeft for the options parameter, the search for matches begins at the end of the input string and moves left; otherwise, the search begins at the start of the input string and moves right.

matchTimeout參數會指定模式比對方法應該在超時之前嘗試尋找相符的時間長度。設定逾時間隔, 可防止依賴過量回溯的正則運算式在處理包含接近相符專案的輸入時, 不會顯示為「停止回應」。The matchTimeout parameter specifies how long a pattern matching method should try to find a match before it times out. Setting a time-out interval prevents regular expressions that rely on excessive backtracking from appearing to "stop responding when they process input that contains near matches. 如需詳細資訊, 請參閱正則運算式和回溯的最佳做法For more information, see Best Practices for Regular Expressions and Backtracking. 如果在該時間間隔內找不到相符的結果, 則RegexMatchTimeoutException方法會擲回例外狀況。If no match is found in that time interval, the method throws a RegexMatchTimeoutException exception. matchTimeout針對方法執行所在的應用程式域, 覆寫任何定義的預設超時值。matchTimeout overrides any default time-out value defined for the application domain in which the method executes.

因為如果沒有相符input專案, 方法會原封不動地傳回, 所以您可以Object.ReferenceEquals使用方法來判斷方法是否已對輸入字串進行任何取代。Because the method returns input unchanged if there is no match, you can use the Object.ReferenceEquals method to determine whether the method has made any replacements to the input string.

給呼叫者的注意事項

我們建議您將matchTimeout參數設定為適當的值, 例如兩秒。We recommend that you set the matchTimeout parameter to an appropriate value, such as two seconds. 如果您藉由指定InfiniteMatchTimeout來停用超時, 則正則運算式引擎可提供稍微較佳的效能。If you disable time-outs by specifying InfiniteMatchTimeout, the regular expression engine offers slightly better performance. 不過, 只有在下列情況下, 您才應該停用超時:However, you should disable time-outs only under the following conditions: -當正則運算式所處理的輸入衍生自已知且受信任的來源, 或包含靜態文字時。- When the input processed by a regular expression is derived from a known and trusted source or consists of static text. 這會排除使用者動態輸入的文字。This excludes text that has been dynamically input by users.

-當正則運算式模式經過徹底測試, 以確保它能有效率地處理相符、不相符和接近的相符專案。- When the regular expression pattern has been thoroughly tested to ensure that it efficiently handles matches, non-matches, and near matches.

-當正則運算式模式未包含任何已知在處理接近相符專案時造成過多回溯的語言元素時。- When the regular expression pattern contains no language elements that are known to cause excessive backtracking when processing a near match.

另請參閱

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

在指定的輸入字串中,使用指定的取代字串來取代符合指定之規則運算式的所有字串。In a specified input string, replaces all strings that match a specified regular expression with a specified replacement string. 如果沒有找到相符項目,其他參數會指定修改比對作業的選項和逾時間隔。Additional parameters specify options that modify the matching operation and a time-out interval if no match is found.

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 String String String

用來搜尋比對的字串。The string to search for a match.

pattern
String String String String

要比對的規則運算式模式。The regular expression pattern to match.

replacement
String String String String

取代字串。The replacement string.

options
RegexOptions RegexOptions RegexOptions RegexOptions

列舉值的位元組合,提供用於比對的選項。A bitwise combination of the enumeration values that provide options for matching.

matchTimeout
TimeSpan TimeSpan TimeSpan TimeSpan

逾時間隔,若要表示此方法不應逾時則為 InfiniteMatchTimeoutA time-out interval, or InfiniteMatchTimeout to indicate that the method should not time out.

傳回

與輸入字串相同的新字串 (不同之處是取代字串會取代每一個相符的字串)。A new string that is identical to the input string, except that the replacement string takes the place of each matched string. 如果在目前的執行個體中沒有符合 pattern 的項目,則方法傳回未變更的目前執行個體。If pattern is not matched in the current instance, the method returns the current instance unchanged.

例外狀況

發生規則運算式剖析錯誤。A regular expression parsing error occurred.

inputpatternreplacementnullinput, pattern, or replacement is null.

options 不是 RegexOptions 值的有效位元組合。options is not a valid bitwise combination of RegexOptions values.

-或--or- matchTimeout 為負數、零或約大於 24 天。matchTimeout is negative, zero, or greater than approximately 24 days.

發生逾時。A time-out occurred. 如需逾時的詳細資訊,請參閱<備註>一節。For more information about time-outs, see the Remarks section.

範例

下列範例會使用Replace(String, String, String, RegexOptions, TimeSpan)方法, 以本機檔案路徑取代 UNC 路徑中的本機電腦和磁片磁碟機名稱。The following example uses the Replace(String, String, String, RegexOptions, TimeSpan) method to replace the local machine and drive names in a UNC path with a local file path. 正則運算式會使用Environment.MachineName屬性來包含本機電腦的名稱Environment.GetLogicalDrives , 以及包含邏輯磁碟機名稱的方法。The regular expression uses the Environment.MachineName property to include the name of the local computer and the Environment.GetLogicalDrives method to include the names of the logical drives. 所有正則運算式字串比較都不區分大小寫, 而且如果在0.5 秒內找不到相符項, 任何單一取代作業會超時。All regular expression string comparisons are case-insensitive, and any single replacement operation times out if a match cannot be found in 0.5 second. 若要成功執行範例, 您應該將常值字串 "MyMachine" 取代為您的本機電腦名稱稱。To run the example successfully, you should replace the literal string "MyMachine" with your local machine name.

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

正則運算式模式是由下列運算式所定義:The regular expression pattern is defined by the following expression:

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

下表顯示規則運算式模式的解譯方式。The following table shows how the regular expression pattern is interpreted.

模式Pattern 說明Description
\\\\ 比對兩個連續\的反斜線 () 字元。\\\\
+ Environment.MachineName + 符合Environment.MachineName屬性所傳回的字串。Match the string that is returned by the Environment.MachineName property.
(?:\.\w+)* 比對後面接著.一或多個文字字元的句號 () 字元。Match the period (.) character followed by one or more word characters. 這項比對可能會出現零次或多次。This match can occur zero or more times. 不會捕捉相符的子運算式。The matched subexpression is not captured.
\\ 比對反斜線\() 字元。\\
([" + driveNames + "]) 符合由個別磁碟機號組成的字元類別。Match the character class that consists of the individual drive letters. 這項比對是第一個已捕獲的子運算式。This match is the first captured subexpression.
\$ 符合常值貨幣符號 ($) 字元。Match the literal dollar sign ($) character.

取代模式$1會使用第一個已捕獲的子運算式來取代整個相符的。The replacement pattern $1 replaces the entire match with the first captured subexpression. 也就是說, 它會以磁碟機號取代 UNC 電腦和磁片磁碟機名稱。That is, it replaces the UNC machine and drive name with the drive letter.

備註

靜態Replace方法相當於使用指定的正Regex則運算式模式來建立物件, 並呼叫實例方法ReplaceThe static Replace methods are equivalent to constructing a Regex object with the specified regular expression pattern and calling the instance method Replace.

pattern 參數包含規則運算式語言項目,以透過符號描述要比對的字串。The pattern parameter consists of regular expression language elements that symbolically describe the string to match. 如需正則運算式的詳細資訊, 請參閱.NET Framework 正則運算式正則運算式語言-快速參考For more information about regular expressions, see .NET Framework Regular Expressions and Regular Expression Language - Quick Reference. 如果為 RightToLeft 參數指定 options,搜尋符合項目會從輸入字串結尾開始向左移動,否則,搜尋會從輸入字串開頭開始向右移動。If you specify RightToLeft for the options parameter, the search for matches begins at the end of the input string and moves left; otherwise, the search begins at the start of the input string and moves right.

參數會指定字串, 以取代中input的每個相符項。 replacementThe replacement parameter specifies the string that is to replace each match in input. replacement可以由常值文字和替代的任何組合所組成。replacement can consist of any combination of literal text and substitutions. 例如, 取代模式a*${test}b會插入字串 "a *", 後面接著test捕捉群組所比對的子字串 (如果有的話), 後面接著字串 "b"。For example, the replacement pattern a*${test}b inserts the string "a*" followed by the substring that is matched by the test capturing group, if any, followed by the string "b". 在取代模式中, 不會將 * 字元辨識為「元字元」。The * character is not recognized as a metacharacter within a replacement pattern.

注意

替代是取代模式中唯一可辨識的正則運算式語言元素。Substitutions are the only regular expression language elements that are recognized in a replacement pattern. 所有其他的正則運算式語言專案, 包括字元的轉義, 都只允許用於正則運算式模式, 而且在取代模式中無法辨識。All other regular expression language elements, including character escapes, are allowed in regular expression patterns only and are not recognized in replacement patterns.

matchTimeout參數會指定模式比對方法應該在超時之前嘗試尋找相符的時間長度。設定逾時間隔, 可防止依賴過量回溯的正則運算式在處理包含接近相符專案的輸入時停止回應。The matchTimeout parameter specifies how long a pattern matching method should try to find a match before it times out. Setting a time-out interval prevents regular expressions that rely on excessive backtracking from appearing to stop responding when they process input that contains near matches. 如需詳細資訊, 請參閱正則運算式和回溯的最佳做法For more information, see Best Practices for Regular Expressions and Backtracking. 如果在該時間間隔內找不到相符的結果, 則RegexMatchTimeoutException方法會擲回例外狀況。If no match is found in that time interval, the method throws a RegexMatchTimeoutException exception. matchTimeout針對方法執行所在的應用程式域, 覆寫任何定義的預設超時值。matchTimeout overrides any default time-out value defined for the application domain in which the method executes.

因為如果沒有相符input專案, 方法會原封不動地傳回, 所以您可以Object.ReferenceEquals使用方法來判斷方法是否已對輸入字串進行任何取代。Because the method returns input unchanged if there is no match, you can use the Object.ReferenceEquals method to determine whether the method has made any replacements to the input string.

給呼叫者的注意事項

我們建議您將matchTimeout參數設定為適當的值, 例如兩秒。We recommend that you set the matchTimeout parameter to an appropriate value, such as two seconds. 如果您藉由指定InfiniteMatchTimeout來停用超時, 則正則運算式引擎可提供稍微較佳的效能。If you disable time-outs by specifying InfiniteMatchTimeout, the regular expression engine offers slightly better performance. 不過, 只有在下列情況下, 您才應該停用超時:However, you should disable time-outs only under the following conditions: -當正則運算式所處理的輸入衍生自已知且受信任的來源, 或包含靜態文字時。- When the input processed by a regular expression is derived from a known and trusted source or consists of static text. 這會排除使用者動態輸入的文字。This excludes text that has been dynamically input by users.

-當正則運算式模式經過徹底測試, 以確保它能有效率地處理相符、不相符和接近的相符專案。- When the regular expression pattern has been thoroughly tested to ensure that it efficiently handles matches, non-matches, and near matches.

-當正則運算式模式未包含任何已知在處理接近相符專案時造成過多回溯的語言元素時。- When the regular expression pattern contains no language elements that are known to cause excessive backtracking when processing a near match.

另請參閱

Replace(String, MatchEvaluator, Int32, Int32) Replace(String, MatchEvaluator, Int32, Int32) Replace(String, MatchEvaluator, Int32, Int32) Replace(String, MatchEvaluator, Int32, Int32)

在指定的輸入子字串中,使用 MatchEvaluator 委派所傳回的字串來取代符合規則運算式模式的指定最大字串數目。In a specified input substring, replaces a specified maximum number of strings that match a regular expression pattern with a string returned by a MatchEvaluator delegate.

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 String String String

用來搜尋比對的字串。The string to search for a match.

evaluator
MatchEvaluator MatchEvaluator MatchEvaluator MatchEvaluator

檢查每個符合項目並傳回原始符合字串或取代字串的自訂方法。A custom method that examines each match and returns either the original matched string or a replacement string.

count
Int32 Int32 Int32 Int32

取代將發生的最多次數。The maximum number of times the replacement will occur.

startat
Int32 Int32 Int32 Int32

在輸入字串中開始搜尋的字元位置。The character position in the input string where the search begins.

傳回

與輸入字串相同的新字串 (不同之處是取代字串會取代每一個相符的字串)。A new string that is identical to the input string, except that a replacement string takes the place of each matched string. 如果規則運算式模式在目前執行個體中沒有符合項目,方法會傳回未變更的目前執行個體。If the regular expression pattern is not matched in the current instance, the method returns the current instance unchanged.

例外狀況

inputevaluatornullinput or evaluator is null.

startat 小於零或大於 input 的長度。startat is less than zero or greater than the length of input.

發生逾時。A time-out occurred. 如需逾時的詳細資訊,請參閱<備註>一節。For more information about time-outs, see the Remarks section.

備註

Regex.Replace(String, MatchEvaluator, Int32, Int32)下列任一條件成立時, 方法適用于取代正則運算式相符:The Regex.Replace(String, MatchEvaluator, Int32, Int32) method is useful for replacing a regular expression match if any of the following conditions is true:

  • 正則運算式取代模式不能輕易地指定取代字串。The replacement string cannot readily be specified by a regular expression replacement pattern.

  • 取代字串會因為在相符的字串上所進行的一些處理而產生。The replacement string results from some processing done on the matched string.

  • 條件式處理的取代字串結果。The replacement string results from conditional processing.

方法相當於Regex.Matches(String, Int32)呼叫方法, 並將傳回MatchCollection之集合中count的第一個Match物件傳遞給evaluator委派。The method is equivalent to calling the Regex.Matches(String, Int32) method and passing the first countMatch objects in the returned MatchCollection collection to the evaluator delegate.

正則運算式是由目前Regex物件的函式所定義的模式。The regular expression is the pattern defined by the constructor for the current Regex object.

evaluator參數是您定義之自訂方法的委派, 它會檢查每個相符的。The evaluator parameter is the delegate for a custom method that you define and that examines each match. 自訂方法必須具有下列簽章, 才能符合MatchEvaluator委派。The custom method must have the following signature to match the MatchEvaluator delegate.

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

您的自訂方法會傳回一個字串, 取代相符的輸入。Your custom method returns a string that replaces the matched input.

如果取代作業的執行時間超出 RegexMatchTimeoutException 建構函式所指定的逾時間隔,就會擲回 Regex.Regex(String, RegexOptions, TimeSpan) 例外狀況。The RegexMatchTimeoutException exception is thrown if the execution time of the replacement operation exceeds the time-out interval specified by the Regex.Regex(String, RegexOptions, TimeSpan) constructor. 呼叫建構函式時若未設定逾時間隔,則如果作業超過為建立 Regex 物件的應用程式定義域設定的任何逾時值,就會擲回例外狀況。If you do not set a time-out interval when you call the constructor, the exception is thrown if the operation exceeds any time-out value established for the application domain in which the Regex object is created. 如果在 Regex 建構函式呼叫或應用程式定義域的屬性中未定義任何逾時,或逾時值是 Regex.InfiniteMatchTimeout,則不擲回任何例外狀況If no time-out is defined in the Regex constructor call or in the application domain's properties, or if the time-out value is Regex.InfiniteMatchTimeout, no exception is thrown

因為如果沒有相符input專案, 方法會原封不動地傳回, 所以您可以Object.ReferenceEquals使用方法來判斷方法是否已對輸入字串進行任何取代。Because the method returns input unchanged if there is no match, you can use the Object.ReferenceEquals method to determine whether the method has made any replacements to the input string.

另請參閱

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

在指定的輸入字串中,使用由 MatchEvaluator 委派所傳回的字串,取代所有與指定之規則運算式相符的字串。In a specified input string, replaces all strings that match a specified regular expression with a string returned by a MatchEvaluator delegate. 指定的選項會修改符合的作業。Specified options modify the matching operation.

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 String String String

用來搜尋比對的字串。The string to search for a match.

pattern
String String String String

要比對的規則運算式模式。The regular expression pattern to match.

evaluator
MatchEvaluator MatchEvaluator MatchEvaluator MatchEvaluator

檢查每個符合項目並傳回原始符合字串或取代字串的自訂方法。A custom method that examines each match and returns either the original matched string or a replacement string.

options
RegexOptions RegexOptions RegexOptions RegexOptions

列舉值的位元組合,提供用於比對的選項。A bitwise combination of the enumeration values that provide options for matching.

傳回

與輸入字串相同的新字串 (不同之處是取代字串會取代每一個相符的字串)。A new string that is identical to the input string, except that a replacement string takes the place of each matched string. 如果在目前的執行個體中沒有符合 pattern 的項目,則方法傳回未變更的目前執行個體。If pattern is not matched in the current instance, the method returns the current instance unchanged.

例外狀況

發生規則運算式剖析錯誤。A regular expression parsing error occurred.

inputpatternevaluatornullinput, pattern, or evaluator is null.

options 不是 RegexOptions 值的有效位元組合。options is not a valid bitwise combination of RegexOptions values.

發生逾時。A time-out occurred. 如需逾時的詳細資訊,請參閱<備註>一節。For more information about time-outs, see the Remarks section.

範例

下列範例會使用正則運算式, 將字串中的個別單字解壓縮, 然後使用MatchEvaluator委派呼叫名為WordScramble的方法, 以將單字中的個別字母進行編碼。The following example uses a regular expression to extract the individual words from a string, and then uses a MatchEvaluator delegate to call a method named WordScramble that scrambles the individual letters in the word. 若要這麼做, WordScramble方法會建立陣列, 其中包含相符的字元。To do this, the WordScramble method creates an array that contains the characters in the match. 它也會建立以隨機浮點數填入的平行陣列。It also creates a parallel array that it populates with random floating-point numbers. 陣列會藉由呼叫Array.Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>)方法來排序, 而且已排序的陣列會當做引數提供給類別的String函式。The arrays are sorted by calling the Array.Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>) method, and the sorted array is provided as an argument to a String class constructor. 這個新建立的WordScramble字串接著會由方法傳回。This newly created string is then returned by the WordScramble method. 正則運算式模式\w+會比對一或多個文字字元, 正則運算式引擎會繼續將字元加入至比對, 直到遇到非文字字元 (如空白字元) 為止。The regular expression pattern \w+ matches one or more word characters; the regular expression engine will continue to add characters to the match until it encounters a non-word character, such as a white-space character. Replace(String, String, MatchEvaluator, RegexOptions)方法的呼叫RegexOptions.IgnorePatternWhitespace包含選項, 因此正則運算式引擎會忽略正則運算式模式\w+ # Matches all the characters in a word.中的批註。The call to the Replace(String, String, MatchEvaluator, RegexOptions) method includes the RegexOptions.IgnorePatternWhitespace option so that the comment in the regular expression pattern \w+ # Matches all the characters in a word. is ignored by the regular expression engine.

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)下列任一條件成立時, 方法適用于取代中的正則運算式相符:The Regex.Replace(String, String, MatchEvaluator, RegexOptions) method is useful for replacing a regular expression match in if any of the following conditions is true:

  • 正則運算式取代模式不能輕易地指定取代字串。The replacement string cannot readily be specified by a regular expression replacement pattern.

  • 取代字串會因為在相符的字串上所進行的一些處理而產生。The replacement string results from some processing done on the matched string.

  • 條件式處理的取代字串結果。The replacement string results from conditional processing.

方法相當Regex.Matches(String, String, RegexOptions)于呼叫方法, 並將傳回MatchCollection之集合Matchevaluator的每個物件傳遞給委派。The method is equivalent to calling the Regex.Matches(String, String, RegexOptions) method and passing each Match object in the returned MatchCollection collection to the evaluator delegate.

pattern 參數包含規則運算式語言項目,以透過符號描述要比對的字串。The pattern parameter consists of regular expression language elements that symbolically describe the string to match. 如需正則運算式的詳細資訊, 請參閱.NET Framework 正則運算式正則運算式語言-快速參考For more information about regular expressions, see .NET Framework Regular Expressions and Regular Expression Language - Quick Reference.

evaluator參數是您定義之自訂方法的委派, 它會檢查每個相符的。The evaluator parameter is the delegate for a custom method that you define and that examines each match. 自訂方法必須具有下列簽章, 才能符合MatchEvaluator委派。The custom method must have the following signature to match the MatchEvaluator delegate.

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

您的自訂方法會傳回一個字串, 取代相符的輸入。Your custom method returns a string that replaces the matched input.

如果為 RightToLeft 參數指定 options,搜尋符合項目會從輸入字串結尾開始向左移動,否則,搜尋會從輸入字串開頭開始向右移動。If you specify RightToLeft for the options parameter, the search for matches begins at the end of the input string and moves left; otherwise, the search begins at the start of the input string and moves right.

如果取代作業的執行時間超出為呼叫方法的應用程式定義域指定的逾時間隔,就會擲回 RegexMatchTimeoutException 例外狀況。The RegexMatchTimeoutException exception is thrown if the execution time of the replacement operation exceeds the time-out interval specified for the application domain in which the method is called. 如果在應用程式定義域的屬性中未定義任何逾時,或逾時值是 Regex.InfiniteMatchTimeout,則不擲回任何例外狀況。If no time-out is defined in the application domain's properties, or if the time-out value is Regex.InfiniteMatchTimeout, no exception is thrown.

因為如果沒有相符input專案, 方法會原封不動地傳回, 所以您可以Object.ReferenceEquals使用方法來判斷方法是否已對輸入字串進行任何取代。Because the method returns input unchanged if there is no match, you can use the Object.ReferenceEquals method to determine whether the method has made any replacements to the input string.

另請參閱

Replace(String, String, Int32, Int32) Replace(String, String, Int32, Int32) Replace(String, String, Int32, Int32) Replace(String, String, Int32, Int32)

在指定的輸入子字串中,使用指定的取代字串來取代符合規則運算式模式的指定最大字串數目。In a specified input substring, replaces a specified maximum number of strings that match a regular expression pattern with a specified replacement string.

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 String String String

用來搜尋比對的字串。The string to search for a match.

replacement
String String String String

取代字串。The replacement string.

count
Int32 Int32 Int32 Int32

取代可以發生的最多次數。Maximum number of times the replacement can occur.

startat
Int32 Int32 Int32 Int32

在輸入字串中開始搜尋的字元位置。The character position in the input string where the search begins.

傳回

與輸入字串相同的新字串 (不同之處是取代字串會取代每一個相符的字串)。A new string that is identical to the input string, except that the replacement string takes the place of each matched string. 如果規則運算式模式在目前執行個體中沒有符合項目,方法會傳回未變更的目前執行個體。If the regular expression pattern is not matched in the current instance, the method returns the current instance unchanged.

例外狀況

inputreplacementnullinput or replacement is null.

startat 小於零或大於 input 的長度。startat is less than zero or greater than the length of input.

發生逾時。A time-out occurred. 如需逾時的詳細資訊,請參閱<備註>一節。For more information about time-outs, see the Remarks section.

範例

下列範例會將字串的第一行以外的所有字元全部加上兩個空格。The following example double-spaces all but the first line of a string. 它會定義符合一行文字的^.*$正則運算式模式、 Match(String)呼叫方法以符合Match.Index字串的第一行, 並使用和Match.Count屬性來判斷第二個的開始位置。連線.It defines a regular expression pattern, ^.*$, that matches a line of text, calls the Match(String) method to match the first line of the string, and uses the Match.Index and Match.Count properties to determine the starting position of the second line.

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.

規則運算式模式 ^.*$ 的定義如下表所示。The regular expression pattern ^.*$ is defined as shown in the following table.

模式Pattern 說明Description
^ 符合行的開頭。Match the start of a line. (請注意Regex , 物件是RegexOptions.Multiline使用選項具現化, 否則這個字元類別只會符合輸入字串的開頭)。(Note that the Regex object was instantiated by using the RegexOptions.Multiline option; otherwise, this character class would only match the beginning of the input string.)
.* 比對任何字元零或多次。Match any character zero or more times.
$ 符合行的結尾。Match the end of a line. (請注意Regex , 物件是RegexOptions.Multiline使用選項具現化, 否則這個字元類別只會符合輸入字串的開頭)。(Note that the Regex object was instantiated by using the RegexOptions.Multiline option; otherwise, this character class would only match the beginning of the input string.)

取代字串 (vbCrLf + "$&"在的"\n$&" Visual Basic 中C#) 會在相符的字串之前加入新的一行。The replacement string (vbCrLf + "$&" in Visual Basic, "\n$&" in C#) adds a new line before the matched string. 請注意, C# C#在此範例中, 編譯器會將其視為分行符號, 而不代表正則運算式字元 escape。 \nNote that \n in the C# example is interpreted as the newline character by the C# compiler; it does not represent a regular expression character escape.

備註

搜尋相符專案會從input startat參數所指定位置的字串開始。The search for matches starts in the input string at the position specified by the startat parameter. 正則運算式是由目前Regex物件的函式所定義的模式。The regular expression is the pattern defined by the constructor for the current Regex object. 如果count是負數, 取代會繼續到字串的結尾。If count is negative, replacements continue to the end of the string. 如果count超過相符專案數目, 則會取代所有相符專案。If count exceeds the number of matches, all matches are replaced.

參數會指定字串, 以取代中input的每個相符項。 replacementThe replacement parameter specifies the string that is to replace each match in input. replacement可以由常值文字和替代的任何組合所組成。replacement can consist of any combination of literal text and substitutions. 例如, 取代模式a*${test}b會插入字串 "a *", 後面接著test捕捉群組所比對的子字串 (如果有的話), 後面接著字串 "b"。For example, the replacement pattern a*${test}b inserts the string "a*" followed by the substring that is matched by the test capturing group, if any, followed by the string "b". 在取代模式中, 不會將 * 字元辨識為「元字元」。The * character is not recognized as a metacharacter within a replacement pattern.

注意

替代是取代模式中唯一可辨識的正則運算式語言元素。Substitutions are the only regular expression language elements that are recognized in a replacement pattern. 所有其他的正則運算式語言專案, 包括字元的轉義, 都只允許用於正則運算式模式, 而且在取代模式中無法辨識。All other regular expression language elements, including character escapes, are allowed in regular expression patterns only and are not recognized in replacement patterns.

如果取代作業的執行時間超出 RegexMatchTimeoutException 建構函式所指定的逾時間隔,就會擲回 Regex.Regex(String, RegexOptions, TimeSpan) 例外狀況。The RegexMatchTimeoutException exception is thrown if the execution time of the replacement operation exceeds the time-out interval specified by the Regex.Regex(String, RegexOptions, TimeSpan) constructor. 呼叫建構函式時若未設定逾時間隔,則如果作業超過為建立 Regex 物件的應用程式定義域設定的任何逾時值,就會擲回例外狀況。If you do not set a time-out interval when you call the constructor, the exception is thrown if the operation exceeds any time-out value established for the application domain in which the Regex object is created. 如果在 Regex 建構函式呼叫或應用程式定義域的屬性中未定義任何逾時,或逾時值是 Regex.InfiniteMatchTimeout,則不擲回任何例外狀況If no time-out is defined in the Regex constructor call or in the application domain's properties, or if the time-out value is Regex.InfiniteMatchTimeout, no exception is thrown

因為如果沒有相符input專案, 方法會原封不動地傳回, 所以您可以Object.ReferenceEquals使用方法來判斷方法是否已對輸入字串進行任何取代。Because the method returns input unchanged if there is no match, you can use the Object.ReferenceEquals method to determine whether the method has made any replacements to the input string.

另請參閱

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

在指定的輸入字串中,使用指定的取代字串來取代符合指定之規則運算式的所有字串。In a specified input string, replaces all strings that match a specified regular expression with a specified replacement string. 指定的選項會修改符合的作業。Specified options modify the matching operation.

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 String String String

用來搜尋比對的字串。The string to search for a match.

pattern
String String String String

要比對的規則運算式模式。The regular expression pattern to match.

replacement
String String String String

取代字串。The replacement string.

options
RegexOptions RegexOptions RegexOptions RegexOptions

列舉值的位元組合,提供用於比對的選項。A bitwise combination of the enumeration values that provide options for matching.

傳回

與輸入字串相同的新字串 (不同之處是取代字串會取代每一個相符的字串)。A new string that is identical to the input string, except that the replacement string takes the place of each matched string. 如果在目前的執行個體中沒有符合 pattern 的項目,則方法傳回未變更的目前執行個體。If pattern is not matched in the current instance, the method returns the current instance unchanged.

例外狀況

發生規則運算式剖析錯誤。A regular expression parsing error occurred.

inputpatternreplacementnullinput, pattern, or replacement is null.

options 不是 RegexOptions 值的有效位元組合。options is not a valid bitwise combination of RegexOptions values.

發生逾時。A time-out occurred. 如需逾時的詳細資訊,請參閱<備註>一節。For more information about time-outs, see the Remarks section.

範例

下列範例會使用Replace(String, String, String, RegexOptions)方法, 以本機檔案路徑取代 UNC 路徑中的本機電腦和磁片磁碟機名稱。The following example uses the Replace(String, String, String, RegexOptions) method to replace the local machine and drive names in a UNC path with a local file path. 正則運算式會使用Environment.MachineName屬性來包含本機電腦的名稱, Environment.GetLogicalDrives以及包含邏輯磁碟機名稱的方法。The regular expression uses the Environment.MachineName property to include the name of the local computer, and the Environment.GetLogicalDrives method to include the names of the logical drives. 所有正則運算式字串比較都不區分大小寫。All regular expression string comparisons are case-insensitive. 若要成功執行範例, 您應該將常值字串 "MyMachine" 取代為您的本機電腦名稱稱。To run the example successfully, you should replace the literal string "MyMachine" with your local machine name.

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

正則運算式模式是由下列運算式所定義:The regular expression pattern is defined by the following expression:

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

下表顯示規則運算式模式的解譯方式。The following table shows how the regular expression pattern is interpreted.

模式Pattern 說明Description
\\\\ 比對兩個連續\的反斜線 () 字元。\\\\
+ Environment.MachineName + 符合Environment.MachineName屬性所傳回的字串。Match the string that is returned by the Environment.MachineName property.
(?:\.\w+)* 比對後面接著.一或多個文字字元的句號 () 字元。Match the period (.) character followed by one or more word characters. 這項比對可能會出現零次或多次。This match can occur zero or more times. 不會捕捉相符的子運算式。The matched subexpression is not captured.
\\ 比對反斜線\() 字元。\\
([" + driveNames + "]) 符合由個別磁碟機號組成的字元類別。Match the character class that consists of the individual drive letters. 這項比對是第一個已捕獲的子運算式。This match is the first captured subexpression.
\$ 符合常值貨幣符號 ($) 字元。Match the literal dollar sign ($) character.

取代模式$1會使用第一個已捕獲的子運算式來取代整個相符的。The replacement pattern $1 replaces the entire match with the first captured subexpression. 也就是說, 它會以磁碟機號取代 UNC 電腦和磁片磁碟機名稱。That is, it replaces the UNC machine and drive name with the drive letter.

備註

靜態Replace方法相當於使用指定的正Regex則運算式模式來建立物件, 並呼叫實例方法ReplaceThe static Replace methods are equivalent to constructing a Regex object with the specified regular expression pattern and calling the instance method Replace.

pattern 參數包含規則運算式語言項目,以透過符號描述要比對的字串。The pattern parameter consists of regular expression language elements that symbolically describe the string to match. 如需正則運算式的詳細資訊, 請參閱.NET Framework 正則運算式正則運算式語言-快速參考For more information about regular expressions, see .NET Framework Regular Expressions and Regular Expression Language - Quick Reference. 如果為 RightToLeft 參數指定 options,搜尋符合項目會從輸入字串結尾開始向左移動,否則,搜尋會從輸入字串開頭開始向右移動。If you specify RightToLeft for the options parameter, the search for matches begins at the end of the input string and moves left; otherwise, the search begins at the start of the input string and moves right.

參數會指定字串, 以取代中input的每個相符項。 replacementThe replacement parameter specifies the string that is to replace each match in input. replacement可以由常值文字和替代的任何組合所組成。replacement can consist of any combination of literal text and substitutions. 例如, 取代模式a*${test}b會插入字串 "a *", 後面接著test捕捉群組所比對的子字串 (如果有的話), 後面接著字串 "b"。For example, the replacement pattern a*${test}b inserts the string "a*" followed by the substring that is matched by the test capturing group, if any, followed by the string "b". 在取代模式中, 不會將 * 字元辨識為「元字元」。The * character is not recognized as a metacharacter within a replacement pattern.

注意

替代是取代模式中唯一可辨識的正則運算式語言元素。Substitutions are the only regular expression language elements that are recognized in a replacement pattern. 所有其他的正則運算式語言專案, 包括字元的轉義, 都只允許用於正則運算式模式, 而且在取代模式中無法辨識。All other regular expression language elements, including character escapes, are allowed in regular expression patterns only and are not recognized in replacement patterns.

如果取代作業的執行時間超出為呼叫方法的應用程式定義域指定的逾時間隔,就會擲回 RegexMatchTimeoutException 例外狀況。The RegexMatchTimeoutException exception is thrown if the execution time of the replacement operation exceeds the time-out interval specified for the application domain in which the method is called. 如果在應用程式定義域的屬性中未定義任何逾時,或逾時值是 Regex.InfiniteMatchTimeout,則不擲回任何例外狀況。If no time-out is defined in the application domain's properties, or if the time-out value is Regex.InfiniteMatchTimeout, no exception is thrown.

因為如果沒有相符input專案, 方法會原封不動地傳回, 所以您可以Object.ReferenceEquals使用方法來判斷方法是否已對輸入字串進行任何取代。Because the method returns input unchanged if there is no match, you can use the Object.ReferenceEquals method to determine whether the method has made any replacements to the input string.

給呼叫者的注意事項

這個方法的逾時間隔等於呼叫這個方法的應用程式定義域的預設逾時值。This method times out after an interval that is equal to the default time-out value of the application domain in which it is called. 如果未針對應用程式定義域定義逾時值,則使用值 InfiniteMatchTimeout,使方法不會逾時。If a time-out value has not been defined for the application domain, the value InfiniteMatchTimeout, which prevents the method from timing out, is used. 取代模式比對的建議靜態方法是Replace(String, String, String, RegexOptions, TimeSpan), 可讓您設定逾時間隔。The recommended static method for replacing a pattern match is Replace(String, String, String, RegexOptions, TimeSpan), which lets you set the time-out interval.

另請參閱

Replace(String, String, MatchEvaluator) Replace(String, String, MatchEvaluator) Replace(String, String, MatchEvaluator) Replace(String, String, MatchEvaluator)

在指定的輸入字串中,使用由 MatchEvaluator 委派所傳回的字串,取代所有與指定之規則運算式相符的字串。In a specified input string, replaces all strings that match a specified regular expression with a string returned by a MatchEvaluator delegate.

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 String String String

用來搜尋比對的字串。The string to search for a match.

pattern
String String String String

要比對的規則運算式模式。The regular expression pattern to match.

evaluator
MatchEvaluator MatchEvaluator MatchEvaluator MatchEvaluator

檢查每個符合項目並傳回原始符合字串或取代字串的自訂方法。A custom method that examines each match and returns either the original matched string or a replacement string.

傳回

與輸入字串相同的新字串 (不同之處是取代字串會取代每一個相符的字串)。A new string that is identical to the input string, except that a replacement string takes the place of each matched string. 如果在目前的執行個體中沒有符合 pattern 的項目,則方法傳回未變更的目前執行個體。If pattern is not matched in the current instance, the method returns the current instance unchanged.

例外狀況

發生規則運算式剖析錯誤。A regular expression parsing error occurred.

inputpatternevaluatornullinput, pattern, or evaluator is null.

發生逾時。A time-out occurred. 如需逾時的詳細資訊,請參閱<備註>一節。For more information about time-outs, see the Remarks section.

範例

下列範例會使用正則運算式, 將字串中的個別單字解壓縮, 然後使用MatchEvaluator委派呼叫名為WordScramble的方法, 以將單字中的個別字母進行編碼。The following example uses a regular expression to extract the individual words from a string, and then uses a MatchEvaluator delegate to call a method named WordScramble that scrambles the individual letters in the word. 若要這麼做, WordScramble方法會建立陣列, 其中包含相符的字元。To do this, the WordScramble method creates an array that contains the characters in the match. 它也會建立以隨機浮點數填入的平行陣列。It also creates a parallel array that it populates with random floating-point numbers. 陣列會藉由呼叫Array.Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>)方法來排序, 而且已排序的陣列會當做引數提供給類別的String函式。The arrays are sorted by calling the Array.Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>) method, and the sorted array is provided as an argument to a String class constructor. 這個新建立的WordScramble字串接著會由方法傳回。This newly created string is then returned by the WordScramble method. 正則運算式模式\w+會比對一或多個文字字元, 正則運算式引擎會繼續將字元加入至比對, 直到遇到非文字字元 (如空白字元) 為止。The regular expression pattern \w+ matches one or more word characters; the regular expression engine will continue to add characters to the match until it encounters a non-word character, such as a white-space character.

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)下列任一條件成立時, 方法適用于取代正則運算式相符:The Regex.Replace(String, String, MatchEvaluator) method is useful for replacing a regular expression match if any of the following conditions is true:

  • 正則運算式取代模式不能輕易地指定取代字串。The replacement string cannot readily be specified by a regular expression replacement pattern.

  • 取代字串會因為在相符的字串上所進行的一些處理而產生。The replacement string results from some processing done on the matched string.

  • 條件式處理的取代字串結果。The replacement string results from conditional processing.

方法相當Regex.Matches(String, String)于呼叫方法, 並將傳回MatchCollection之集合Matchevaluator的每個物件傳遞給委派。The method is equivalent to calling the Regex.Matches(String, String) method and passing each Match object in the returned MatchCollection collection to the evaluator delegate.

pattern 參數包含規則運算式語言項目,以透過符號描述要比對的字串。The pattern parameter consists of regular expression language elements that symbolically describe the string to match. 如需正則運算式的詳細資訊, 請參閱.NET Framework 正則運算式正則運算式語言-快速參考For more information about regular expressions, see .NET Framework Regular Expressions and Regular Expression Language - Quick Reference.

evaluator參數是您定義之自訂方法的委派, 它會檢查每個相符的。The evaluator parameter is the delegate for a custom method that you define and that examines each match. 自訂方法必須具有下列簽章, 才能符合MatchEvaluator委派。The custom method must have the following signature to match the MatchEvaluator delegate.

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

您的自訂方法會傳回一個字串, 取代相符的輸入。Your custom method returns a string that replaces the matched input.

如果取代作業的執行時間超出為呼叫方法的應用程式定義域指定的逾時間隔,就會擲回 RegexMatchTimeoutException 例外狀況。The RegexMatchTimeoutException exception is thrown if the execution time of the replacement operation exceeds the time-out interval specified for the application domain in which the method is called. 如果在應用程式定義域的屬性中未定義任何逾時,或逾時值是 Regex.InfiniteMatchTimeout,則不擲回任何例外狀況。If no time-out is defined in the application domain's properties, or if the time-out value is Regex.InfiniteMatchTimeout, no exception is thrown.

因為如果沒有相符input專案, 方法會原封不動地傳回, 所以您可以Object.ReferenceEquals使用方法來判斷方法是否已對輸入字串進行任何取代。Because the method returns input unchanged if there is no match, you can use the Object.ReferenceEquals method to determine whether the method has made any replacements to the input string.

給呼叫者的注意事項

這個方法的逾時間隔等於呼叫這個方法的應用程式定義域的預設逾時值。This method times out after an interval that is equal to the default time-out value of the application domain in which it is called. 如果未針對應用程式定義域定義逾時值,則使用值 InfiniteMatchTimeout,使方法不會逾時。If a time-out value has not been defined for the application domain, the value InfiniteMatchTimeout, which prevents the method from timing out, is used. 評估和取代模式比對的建議靜態方法是Replace(String, String, MatchEvaluator, RegexOptions, TimeSpan), 可讓您設定逾時間隔。The recommended static method for evaluating and replacing a pattern match is Replace(String, String, MatchEvaluator, RegexOptions, TimeSpan), which lets you set the time-out interval.

另請參閱

Replace(String, String, String) Replace(String, String, String) Replace(String, String, String) Replace(String, String, String)

在指定的輸入字串中,使用指定的取代字串來取代符合指定之規則運算式的所有字串。In a specified input string, replaces all strings that match a specified regular expression with a specified replacement 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 String String String

用來搜尋比對的字串。The string to search for a match.

pattern
String String String String

要比對的規則運算式模式。The regular expression pattern to match.

replacement
String String String String

取代字串。The replacement string.

傳回

與輸入字串相同的新字串 (不同之處是取代字串會取代每一個相符的字串)。A new string that is identical to the input string, except that the replacement string takes the place of each matched string. 如果在目前的執行個體中沒有符合 pattern 的項目,則方法傳回未變更的目前執行個體。If pattern is not matched in the current instance, the method returns the current instance unchanged.

例外狀況

發生規則運算式剖析錯誤。A regular expression parsing error occurred.

inputpatternreplacementnullinput, pattern, or replacement is null.

發生逾時。A time-out occurred. 如需逾時的詳細資訊,請參閱<備註>一節。For more information about time-outs, see the Remarks section.

範例

下列範例會定義符合一或多\s+個空白字元的正則運算式。The following example defines a regular expression, \s+, that matches one or more white-space characters. 取代字串 "" 會以單一空白字元取代它們。The replacement string, " ", replaces them with a single space character.

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 路徑中的本機電腦和磁片磁碟機名稱。The following example uses the Replace(String, String, String) method to replace the local machine and drive names in a UNC path with a local file path. 正則運算式會使用Environment.MachineName屬性來包含本機電腦的名稱, Environment.GetLogicalDrives以及包含邏輯磁碟機名稱的方法。The regular expression uses the Environment.MachineName property to include the name of the local computer, and the Environment.GetLogicalDrives method to include the names of the logical drives. 若要成功執行範例, 您應該將常值字串 "MyMachine" 取代為您的本機電腦名稱稱。To run the example successfully, you should replace the literal string "MyMachine" with your local machine name.

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

正則運算式模式是由下列運算式所定義:The regular expression pattern is defined by the following expression:

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

下表顯示規則運算式模式的解譯方式。The following table shows how the regular expression pattern is interpreted.

模式Pattern 說明Description
\\\\ 比對兩個連續\的反斜線 () 字元。\\\\
(?i:" + Environment.MachineName + ") 執行Environment.MachineName屬性所傳回之字串的不區分大小寫比對。Perform a case-insensitive match of the string that is returned by the Environment.MachineName property.
(?:\.\w+)* 比對後面接著.一或多個文字字元的句號 () 字元。Match the period (.) character followed by one or more word characters. 這項比對可能會出現零次或多次。This match can occur zero or more times. 不會捕捉相符的子運算式。The matched subexpression is not captured.
\\ 比對反斜線\() 字元。\\
((?i:[" + driveNames + "])) 執行包含個別磁碟機號之字元類別的不區分大小寫比對。Perform a case-insensitive match of the character class that consists of the individual drive letters. 這項比對是第一個已捕獲的子運算式。This match is the first captured subexpression.
\$ 符合常值貨幣符號 ($) 字元。Match the literal dollar sign ($) character.

取代模式$1會使用第一個已捕獲的子運算式來取代整個相符的。The replacement pattern $1 replaces the entire match with the first captured subexpression. 也就是說, 它會以磁碟機號取代 UNC 電腦和磁片磁碟機名稱。That is, it replaces the UNC machine and drive name with the drive letter.

備註

靜態Replace方法相當於使用指定的正Regex則運算式模式來建立物件, 並呼叫實例方法ReplaceThe static Replace methods are equivalent to constructing a Regex object with the specified regular expression pattern and calling the instance method Replace.

pattern 參數包含規則運算式語言項目,以透過符號描述要比對的字串。The pattern parameter consists of regular expression language elements that symbolically describe the string to match. 如需正則運算式的詳細資訊, 請參閱.NET Framework 正則運算式正則運算式語言-快速參考For more information about regular expressions, see .NET Framework Regular Expressions and Regular Expression Language - Quick Reference. 搜尋符合專案會從input字串的開頭開始。The search for matches starts at the beginning of the input string.

參數會指定字串, 以取代中input的每個相符項。 replacementThe replacement parameter specifies the string that is to replace each match in input. replacement可以由常值文字和替代的任何組合所組成。replacement can consist of any combination of literal text and substitutions. 例如, 取代模式a*${test}b會插入字串 "a *", 後面接著test捕捉群組所比對的子字串 (如果有的話), 後面接著字串 "b"。For example, the replacement pattern a*${test}b inserts the string "a*" followed by the substring that is matched by the test capturing group, if any, followed by the string "b". 在取代模式中, 不會將 * 字元辨識為「元字元」。The * character is not recognized as a metacharacter within a replacement pattern.

注意

替代是取代模式中唯一可辨識的正則運算式語言元素。Substitutions are the only regular expression language elements that are recognized in a replacement pattern. 所有其他的正則運算式語言專案, 包括字元的轉義, 都只允許用於正則運算式模式, 而且在取代模式中無法辨識。All other regular expression language elements, including character escapes, are allowed in regular expression patterns only and are not recognized in replacement patterns.

如果取代作業的執行時間超出為呼叫方法的應用程式定義域指定的逾時間隔,就會擲回 RegexMatchTimeoutException 例外狀況。The RegexMatchTimeoutException exception is thrown if the execution time of the replacement operation exceeds the time-out interval specified for the application domain in which the method is called. 如果在應用程式定義域的屬性中未定義任何逾時,或逾時值是 Regex.InfiniteMatchTimeout,則不擲回任何例外狀況。If no time-out is defined in the application domain's properties, or if the time-out value is Regex.InfiniteMatchTimeout, no exception is thrown.

因為如果沒有相符input專案, 方法會原封不動地傳回, 所以您可以Object.ReferenceEquals使用方法來判斷方法是否已對輸入字串進行任何取代。Because the method returns input unchanged if there is no match, you can use the Object.ReferenceEquals method to determine whether the method has made any replacements to the input string.

給呼叫者的注意事項

這個方法的逾時間隔等於呼叫這個方法的應用程式定義域的預設逾時值。This method times out after an interval that is equal to the default time-out value of the application domain in which it is called. 如果未針對應用程式定義域定義逾時值,則使用值 InfiniteMatchTimeout,使方法不會逾時。If a time-out value has not been defined for the application domain, the value InfiniteMatchTimeout, which prevents the method from timing out, is used. 取代模式比對的建議靜態方法是Replace(String, String, String, RegexOptions, TimeSpan), 可讓您設定逾時間隔。The recommended static method for replacing a pattern match is Replace(String, String, String, RegexOptions, TimeSpan), which lets you set the time-out interval.

另請參閱

Replace(String, String, Int32) Replace(String, String, Int32) Replace(String, String, Int32) Replace(String, String, Int32)

在指定的輸入字串中,使用指定的取代字串來取代符合規則運算式模式的指定最大字串數目。In a specified input string, replaces a specified maximum number of strings that match a regular expression pattern with a specified replacement string.

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 String String String

用來搜尋比對的字串。The string to search for a match.

replacement
String String String String

取代字串。The replacement string.

count
Int32 Int32 Int32 Int32

取代作業可以發生的最大次數。The maximum number of times the replacement can occur.

傳回

與輸入字串相同的新字串 (不同之處是取代字串會取代每一個相符的字串)。A new string that is identical to the input string, except that the replacement string takes the place of each matched string. 如果規則運算式模式在目前執行個體中沒有符合項目,方法會傳回未變更的目前執行個體。If the regular expression pattern is not matched in the current instance, the method returns the current instance unchanged.

例外狀況

inputreplacementnullinput or replacement is null.

發生逾時。A time-out occurred. 如需逾時的詳細資訊,請參閱<備註>一節。For more information about time-outs, see the Remarks section.

範例

下列範例會以單一字元取代重複字元的前五個出現專案。The following example replaces the first five occurrences of duplicated characters with a single character. 正則運算式模式(\w)\1會比對單一字元的連續出現專案, 並將第一個出現的專案指派給第一個「捕獲群組」。The regular expression pattern (\w)\1 matches consecutive occurrences of a single character and assigns the first occurrence to the first capturing group. 取代模式$1會將整個相符項取代為第一個已捕獲的群組。The replacement pattern $1 replaces the entire match with the first captured group.

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字串的開頭開始。The search for matches starts at the beginning of the input string. 正則運算式是由目前Regex物件的函式所定義的模式。The regular expression is the pattern that is defined by the constructor for the current Regex object. 如果count是負數, 取代會繼續到字串的結尾。If count is negative, replacements continue to the end of the string. 如果count超過相符專案數目, 則會取代所有相符專案。If count exceeds the number of matches, all matches are replaced.

參數會指定字串, 以取代中input的第一個count相符專案。 replacementThe replacement parameter specifies the string that is to replace the first count matches in input. replacement可以由常值文字和替代的任何組合所組成。replacement can consist of any combination of literal text and substitutions. 例如, 取代模式a*${test}b會插入字串 "a *", 後面接著test捕捉群組所比對的子字串 (如果有的話), 後面接著字串 "b"。For example, the replacement pattern a*${test}b inserts the string "a*" followed by the substring that is matched by the test capturing group, if any, followed by the string "b". 在取代模式中, 不會將 * 字元辨識為「元字元」。The * character is not recognized as a metacharacter within a replacement pattern.

注意

替代是取代模式中唯一可辨識的正則運算式語言元素。Substitutions are the only regular expression language elements that are recognized in a replacement pattern. 所有其他的正則運算式語言專案, 包括字元的轉義, 都只允許用於正則運算式模式, 而且在取代模式中無法辨識。All other regular expression language elements, including character escapes, are allowed in regular expression patterns only and are not recognized in replacement patterns.

如果取代作業的執行時間超出 RegexMatchTimeoutException 建構函式所指定的逾時間隔,就會擲回 Regex.Regex(String, RegexOptions, TimeSpan) 例外狀況。The RegexMatchTimeoutException exception is thrown if the execution time of the replacement operation exceeds the time-out interval specified by the Regex.Regex(String, RegexOptions, TimeSpan) constructor. 呼叫建構函式時若未設定逾時間隔,則如果作業超過為建立 Regex 物件的應用程式定義域設定的任何逾時值,就會擲回例外狀況。If you do not set a time-out interval when you call the constructor, the exception is thrown if the operation exceeds any time-out value established for the application domain in which the Regex object is created. 如果在 Regex 建構函式呼叫或應用程式定義域的屬性中未定義任何逾時,或逾時值是 Regex.InfiniteMatchTimeout,則不擲回任何例外狀況If no time-out is defined in the Regex constructor call or in the application domain's properties, or if the time-out value is Regex.InfiniteMatchTimeout, no exception is thrown

因為如果沒有相符input專案, 方法會原封不動地傳回, 所以您可以Object.ReferenceEquals使用方法來判斷方法是否已對輸入字串進行任何取代。Because the method returns input unchanged if there is no match, you can use the Object.ReferenceEquals method to determine whether the method has made any replacements to the input string.

另請參閱

Replace(String, MatchEvaluator) Replace(String, MatchEvaluator) Replace(String, MatchEvaluator) Replace(String, MatchEvaluator)

在指定的輸入字串中,使用由 MatchEvaluator 委派所傳回的字串,取代所有與指定之規則運算式相符的字串。In a specified input string, replaces all strings that match a specified regular expression with a string returned by a MatchEvaluator delegate.

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 String String String

用來搜尋比對的字串。The string to search for a match.

evaluator
MatchEvaluator MatchEvaluator MatchEvaluator MatchEvaluator

檢查每個符合項目並傳回原始符合字串或取代字串的自訂方法。A custom method that examines each match and returns either the original matched string or a replacement string.

傳回

與輸入字串相同的新字串 (不同之處是取代字串會取代每一個相符的字串)。A new string that is identical to the input string, except that a replacement string takes the place of each matched string. 如果規則運算式模式在目前執行個體中沒有符合項目,方法會傳回未變更的目前執行個體。If the regular expression pattern is not matched in the current instance, the method returns the current instance unchanged.

例外狀況

inputevaluatornullinput or evaluator is null.

發生逾時。A time-out occurred. 如需逾時的詳細資訊,請參閱<備註>一節。For more information about time-outs, see the Remarks section.

範例

下列程式碼範例會顯示原始字串、比對原始字串中的每個單字、將每個相符專案的第一個字元轉換成大寫, 然後顯示已轉換的字串。The following code example displays an original string, matches each word in the original string, converts the first character of each match to uppercase, then displays the converted string.

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)下列任一條件成立時, 方法適用于取代正則運算式相符:The Regex.Replace(String, MatchEvaluator) method is useful for replacing a regular expression match if any of the following conditions is true:

  • 正則運算式取代模式不能輕易地指定取代字串。The replacement string cannot readily be specified by a regular expression replacement pattern.

  • 取代字串會因為在相符的字串上所進行的一些處理而產生。The replacement string results from some processing done on the matched string.

  • 條件式處理的取代字串結果。The replacement string results from conditional processing.

方法相當Regex.Matches(String)于呼叫方法, 並將傳回MatchCollection之集合Matchevaluator的每個物件傳遞給委派。The method is equivalent to calling the Regex.Matches(String) method and passing each Match object in the returned MatchCollection collection to the evaluator delegate.

正則運算式是由目前Regex物件的函式所定義的模式。The regular expression is the pattern defined by the constructor for the current Regex object.

evaluator參數是您定義之自訂方法的委派, 它會檢查每個相符的。The evaluator parameter is the delegate for a custom method that you define and that examines each match. 自訂方法必須具有下列簽章, 才能符合MatchEvaluator委派。The custom method must have the following signature to match the MatchEvaluator delegate.

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

您的自訂方法會傳回一個字串, 取代相符的輸入。Your custom method returns a string that replaces the matched input.

如果取代作業的執行時間超出 RegexMatchTimeoutException 建構函式所指定的逾時間隔,就會擲回 Regex.Regex(String, RegexOptions, TimeSpan) 例外狀況。The RegexMatchTimeoutException exception is thrown if the execution time of the replacement operation exceeds the time-out interval specified by the Regex.Regex(String, RegexOptions, TimeSpan) constructor. 呼叫建構函式時若未設定逾時間隔,則如果作業超過為建立 Regex 物件的應用程式定義域設定的任何逾時值,就會擲回例外狀況。If you do not set a time-out interval when you call the constructor, the exception is thrown if the operation exceeds any time-out value established for the application domain in which the Regex object is created. 如果在 Regex 建構函式呼叫或應用程式定義域的屬性中未定義任何逾時,或逾時值是 Regex.InfiniteMatchTimeout,則不擲回任何例外狀況If no time-out is defined in the Regex constructor call or in the application domain's properties, or if the time-out value is Regex.InfiniteMatchTimeout, no exception is thrown

因為如果沒有相符input專案, 方法會原封不動地傳回, 所以您可以Object.ReferenceEquals使用方法來判斷方法是否已對輸入字串進行任何取代。Because the method returns input unchanged if there is no match, you can use the Object.ReferenceEquals method to determine whether the method has made any replacements to the input string.

另請參閱

Replace(String, String) Replace(String, String) Replace(String, String) Replace(String, String)

在指定的輸入字串中,使用指定的取代字串來取代符合規則運算式模式的所有字串。In a specified input string, replaces all strings that match a regular expression pattern with a specified replacement 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 String String String

用來搜尋比對的字串。The string to search for a match.

replacement
String String String String

取代字串。The replacement string.

傳回

與輸入字串相同的新字串 (不同之處是取代字串會取代每一個相符的字串)。A new string that is identical to the input string, except that the replacement string takes the place of each matched string. 如果規則運算式模式在目前執行個體中沒有符合項目,方法會傳回未變更的目前執行個體。If the regular expression pattern is not matched in the current instance, the method returns the current instance unchanged.

例外狀況

inputreplacementnullinput or replacement is null.

發生逾時。A time-out occurred. 如需逾時的詳細資訊,請參閱<備註>一節。For more information about time-outs, see the Remarks section.

範例

下列範例會定義符合一或多\s+個空白字元的正則運算式。The following example defines a regular expression, \s+, that matches one or more white-space characters. 取代字串 "" 會以單一空白字元取代它們。The replacement string, " ", replaces them with a single space character.

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這會從數值中移除前置或尾端貨幣符號。The following example defines a regular expression, (\p{Sc}\s?)?(\d+\.?((?<=\.)\d+)?)(?(1)|\s?\p{Sc})?, and a replacement pattern, $2, that removes either a leading or a trailing currency symbol from a numeric value.

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'

規則運算式的解譯方式如下表所示。The regular expression is interpreted as shown in the following table.

模式Pattern 說明Description
\p{Sc} 符合貨幣符號。Match a currency symbol. {Sc}表示屬於 Unicode 符號 Currency 類別目錄成員的任何字元。{Sc} denotes any character that is a member of the Unicode Symbol, Currency category.
\s? 比對零個或一個空白字元。Match zero or one white-space character.
(\p{Sc}\s?)? 比對符合零或一次的貨幣符號組合, 後面接著零或一個空白字元。Match zero or one occurrence of the combination of a currency symbol followed by zero or one white-space character. 這是第一個擷取群組。This is the first capturing group.
\d+ 比對一個或多個十進位數字。Match one or more decimal digits.
\.? 比對零或一次出現的句號 (用來做為小數分隔字元)。Match zero or one occurrence of a period (used as a decimal separator character).
((?<=\.)\d+)? 如果句點是前一個字元, 則比對一或多個十進位數。If a period is the previous character, match one or more decimal digits. 此模式可比對零或一次。This pattern can be matched either zero or one time.
(\d+\.?((?<=\.)\d+)?) 比對一或多個十進位數的模式, 後面接著選擇性的句點和其他小數位數。Match the pattern of one or more decimal digits followed by an optional period and additional decimal digits. 這是第二個擷取群組。This is the second capturing group. Replace(String, String)方法的呼叫會將整個相符項取代為這個已捕獲群組的值。The call to the Replace(String, String) method replaces the entire match with the value of this captured group.
(?(1)|\s?\p{Sc})? 如果第一個已捕獲的群組存在, 則符合空字串。If the first captured group exists, match an empty string. 否則, 比對零個或一個空白字元, 後面接著貨幣符號。Otherwise, match zero or one white-space character followed by a currency symbol.

備註

搜尋符合專案會從input字串的開頭開始。The search for matches starts at the beginning of the input string. 正則運算式是由目前Regex物件的函式所定義的模式。The regular expression is the pattern defined by the constructor for the current Regex object.

參數會指定字串, 以取代中input的每個相符項。 replacementThe replacement parameter specifies the string that is to replace each match in input. replacement可以由常值文字和替代的任何組合所組成。replacement can consist of any combination of literal text and substitutions. 例如, 取代模式a*${test}b會插入字串 "a *", 後面接著test捕捉群組所比對的子字串 (如果有的話), 後面接著字串 "b"。For example, the replacement pattern a*${test}b inserts the string "a*" followed by the substring that is matched by the test capturing group, if any, followed by the string "b". 在取代模式中, 不會將 * 字元辨識為「元字元」。The * character is not recognized as a metacharacter within a replacement pattern.

注意

替代是取代模式中唯一可辨識的正則運算式語言元素。Substitutions are the only regular expression language elements that are recognized in a replacement pattern. 所有其他的正則運算式語言專案, 包括字元的轉義, 都只允許用於正則運算式模式, 而且在取代模式中無法辨識。All other regular expression language elements, including character escapes, are allowed in regular expression patterns only and are not recognized in replacement patterns.

如果取代作業的執行時間超出 RegexMatchTimeoutException 建構函式所指定的逾時間隔,就會擲回 Regex.Regex(String, RegexOptions, TimeSpan) 例外狀況。The RegexMatchTimeoutException exception is thrown if the execution time of the replacement operation exceeds the time-out interval specified by the Regex.Regex(String, RegexOptions, TimeSpan) constructor. 呼叫建構函式時若未設定逾時間隔,則如果作業超過為建立 Regex 物件的應用程式定義域設定的任何逾時值,就會擲回例外狀況。If you do not set a time-out interval when you call the constructor, the exception is thrown if the operation exceeds any time-out value established for the application domain in which the Regex object is created. 如果在 Regex 建構函式呼叫或應用程式定義域的屬性中未定義任何逾時,或逾時值是 Regex.InfiniteMatchTimeout,則不擲回任何例外狀況If no time-out is defined in the Regex constructor call or in the application domain's properties, or if the time-out value is Regex.InfiniteMatchTimeout, no exception is thrown

因為如果沒有相符input專案, 方法會原封不動地傳回, 所以您可以Object.ReferenceEquals使用方法來判斷方法是否已對輸入字串進行任何取代。Because the method returns input unchanged if there is no match, you can use the Object.ReferenceEquals method to determine whether the method has made any replacements to the input string.

另請參閱

Replace(String, MatchEvaluator, Int32) Replace(String, MatchEvaluator, Int32) Replace(String, MatchEvaluator, Int32) Replace(String, MatchEvaluator, Int32)

在指定的輸入字串中,使用 MatchEvaluator 委派所傳回的字串來取代符合規則運算式模式的指定最大字串數目。In a specified input string, replaces a specified maximum number of strings that match a regular expression pattern with a string returned by a MatchEvaluator delegate.

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 String String String

用來搜尋比對的字串。The string to search for a match.

evaluator
MatchEvaluator MatchEvaluator MatchEvaluator MatchEvaluator

檢查每個符合項目並傳回原始符合字串或取代字串的自訂方法。A custom method that examines each match and returns either the original matched string or a replacement string.

count
Int32 Int32 Int32 Int32

取代將發生的最多次數。The maximum number of times the replacement will occur.

傳回

與輸入字串相同的新字串 (不同之處是取代字串會取代每一個相符的字串)。A new string that is identical to the input string, except that a replacement string takes the place of each matched string. 如果規則運算式模式在目前執行個體中沒有符合項目,方法會傳回未變更的目前執行個體。If the regular expression pattern is not matched in the current instance, the method returns the current instance unchanged.

例外狀況

inputevaluatornullinput or evaluator is null.

發生逾時。A time-out occurred. 如需逾時的詳細資訊,請參閱<備註>一節。For more information about time-outs, see the Remarks section.

範例

下列範例會使用正則運算式, 故意拼錯清單中的一半字。The following example uses a regular expression to deliberately misspell half of the words in a list. 它會使用正則\w*(ie|ei)\w*運算式來比對包含字元 "ie" 或 "ei" 的文字。It uses the regular expression \w*(ie|ei)\w* to match words that include the characters "ie" or "ei". 它會將比對單字的前一半傳遞至ReverseLetter方法, 而後者接著會Replace(String, String, String, RegexOptions)使用方法, 在相符的字串中反轉 "i" 和 "e"。It passes the first half of the matching words to the ReverseLetter method, which, in turn, uses the Replace(String, String, String, RegexOptions) method to reverse "i" and "e" in the matched string. 其餘的文字會保持不變。The remaining words remain unchanged.

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* 的定義如下表所示。The regular expression \w*(ie|ei)\w* is defined as shown in the following table.

模式Pattern 說明Description
\w* 比對零個或多個文字字元。Match zero or more word characters.
(ie|ei) 符合 "ie" 或 "ei"。Match either "ie" or "ei".
\w* 比對零個或多個文字字元。Match zero or more word characters.

方法中的正([ie])([ie])則運算式模式會比對 diphthong "ie" 或 "ei" 中的第一個 "i" 或 "e", 並將該字母指派給第一個捕獲群組。 ReverseLetterThe regular expression pattern ([ie])([ie]) in the ReverseLetter method matches the first "i" or "e" in the diphthong "ie" or "ei" and assigns the letter to the first capturing group. 它符合第二個 "i" 或 "e", 並將字母指派給第二個捕獲群組。It matches the second "i" or "e" and assigns the letter to the second capturing group. 然後使用取代模式Replace(String, String, String) $2$1來呼叫方法, 以反轉這兩個字元。The two characters are then reversed by calling the Replace(String, String, String) method with the replacement pattern $2$1.

備註

Regex.Replace(String, MatchEvaluator, Int32)下列任一條件成立時, 方法適用于取代正則運算式相符:The Regex.Replace(String, MatchEvaluator, Int32) method is useful for replacing a regular expression match if any of the following conditions is true:

  • 正則運算式取代模式不能輕易地指定取代字串。The replacement string cannot readily be specified by a regular expression replacement pattern.

  • 取代字串會因為在相符的字串上所進行的一些處理而產生。The replacement string results from some processing done on the matched string.

  • 條件式處理的取代字串結果。The replacement string results from conditional processing.

方法相當於Regex.Matches(String)呼叫方法, 並將傳回MatchCollection之集合中count的第一個Match物件傳遞給evaluator委派。The method is equivalent to calling the Regex.Matches(String) method and passing the first countMatch objects in the returned MatchCollection collection to the evaluator delegate.

正則運算式是由目前Regex物件的函式所定義的模式。The regular expression is the pattern defined by the constructor for the current Regex object.

evaluator參數是您定義之自訂方法的委派, 它會檢查每個相符的。The evaluator parameter is the delegate for a custom method that you define and that examines each match. 自訂方法必須具有下列簽章, 才能符合MatchEvaluator委派。The custom method must have the following signature to match the MatchEvaluator delegate.

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

您的自訂方法會傳回一個字串, 取代相符的輸入。Your custom method returns a string that replaces the matched input.

如果取代作業的執行時間超出 RegexMatchTimeoutException 建構函式所指定的逾時間隔,就會擲回 Regex.Regex(String, RegexOptions, TimeSpan) 例外狀況。The RegexMatchTimeoutException exception is thrown if the execution time of the replacement operation exceeds the time-out interval specified by the Regex.Regex(String, RegexOptions, TimeSpan) constructor. 呼叫建構函式時若未設定逾時間隔,則如果作業超過為建立 Regex 物件的應用程式定義域設定的任何逾時值,就會擲回例外狀況。If you do not set a time-out interval when you call the constructor, the exception is thrown if the operation exceeds any time-out value established for the application domain in which the Regex object is created. 如果在 Regex 建構函式呼叫或應用程式定義域的屬性中未定義任何逾時,或逾時值是 Regex.InfiniteMatchTimeout,則不擲回任何例外狀況If no time-out is defined in the Regex constructor call or in the application domain's properties, or if the time-out value is Regex.InfiniteMatchTimeout, no exception is thrown

因為如果沒有相符input專案, 方法會原封不動地傳回, 所以您可以Object.ReferenceEquals使用方法來判斷方法是否已對輸入字串進行任何取代。Because the method returns input unchanged if there is no match, you can use the Object.ReferenceEquals method to determine whether the method has made any replacements to the input string.

另請參閱

適用於