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)方法并传递每个Match在返回的对象MatchCollection集合evaluator委托。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.

如果指定RightToLeftoptions参数,搜索的匹配项从输入字符串的末尾处开始,并向左移动; 否则为搜索输入字符串的开头开始并向右移动。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
\\\\ 匹配两个连续反斜杠 (\) 字符。Match two consecutive backslash (\) characters. 反斜杠字符解释为转义符,因为每个反斜杠必须使用另一个反斜杠进行转义。Because the backslash character is interpreted as the escape character, each backslash must be escaped with another backslash.
+ 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.
\\ 匹配一个反斜杠 (\) 字符。Match a backslash (\) character.
([" + 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. 如果指定RightToLeftoptions参数,搜索的匹配项从输入字符串的末尾处开始,并向左移动; 否则为搜索输入字符串的开头开始并向右移动。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.

replacement参数指定是替换中的每个匹配项的字符串inputThe 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插入字符串"*"匹配的子字符串后跟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)方法并传递第一个countMatch中返回的对象MatchCollection集合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)方法并传递每个Match在返回的对象MatchCollection集合evaluator委托。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.

如果指定RightToLeftoptions参数,搜索的匹配项从输入字符串的末尾处开始,并向左移动; 否则为搜索输入字符串的开头开始并向右移动。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.

示例

除字符串的第一行之外的所有 double-spaces 下面的示例。The following example double-spaces all but the first line of a string. 它定义的正则表达式模式^.*$,与匹配的文本,调用行Match(String)方法以匹配的字符串,并使用第一行Match.IndexMatch.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 + "$&"在 Visual Basic 中"\n$&"C# 中) 添加一个新行之前匹配的字符串。The replacement string (vbCrLf + "$&" in Visual Basic, "\n$&" in C#) adds a new line before the matched string. 请注意,\n在 C# 示例将解释为换行字符由 C# 编译器; 它不表示正则表达式字符转义符。Note 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.

replacement参数指定是替换中的每个匹配项的字符串inputThe 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插入字符串"*"匹配的子字符串后跟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
\\\\ 匹配两个连续反斜杠 (\) 字符。Match two consecutive backslash (\) characters. 反斜杠字符解释为转义符,因为每个反斜杠必须使用另一个反斜杠进行转义。Because the backslash character is interpreted as the escape character, each backslash must be escaped with another backslash.
+ 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.
\\ 匹配一个反斜杠 (\) 字符。Match a backslash (\) character.
([" + 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. 如果指定RightToLeftoptions参数,搜索的匹配项从输入字符串的末尾处开始,并向左移动; 否则为搜索输入字符串的开头开始并向右移动。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.

replacement参数指定是替换中的每个匹配项的字符串inputThe 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插入字符串"*"匹配的子字符串后跟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)方法并传递每个Match在返回的对象MatchCollection集合evaluator委托。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
\\\\ 匹配两个连续反斜杠 (\) 字符。Match two consecutive backslash (\) characters. 反斜杠字符解释为转义符,因为每个反斜杠必须使用另一个反斜杠进行转义。Because the backslash character is interpreted as the escape character, each backslash must be escaped with another backslash.
(?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.
\\ 匹配一个反斜杠 (\) 字符。Match a backslash (\) character.
((?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.

replacement参数指定是替换中的每个匹配项的字符串inputThe 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插入字符串"*"匹配的子字符串后跟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.

replacement参数指定的字符串,用于替换第一个count一致inputThe 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插入字符串"*"匹配的子字符串后跟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)方法并传递每个Match在返回的对象MatchCollection集合evaluator委托。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 符号、 货币类别的成员。{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.

replacement参数指定是替换中的每个匹配项的字符串inputThe 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插入字符串"*"匹配的子字符串后跟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])ReverseLetter方法 diphthong"ie"或"ei"中匹配的第一个"i"或"e",并将字母分配给第一个捕获组。The 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$1The 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)方法并传递第一个countMatch中返回的对象MatchCollection集合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.

另请参阅

适用于