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将返回集合中的每个对象传递给委托。evaluatorThe method is equivalent to calling the Regex.Matches(String, String, RegexOptions) method and passing each Match object in the returned MatchCollection collection to the evaluator delegate.

pattern参数包含符号描述要匹配的字符串的正则表达式语言元素。The pattern parameter consists of regular expression language elements that symbolically describe the string to match. 有关正则表达式的详细信息, 请参阅.NET Framework 正则表达式正则表达式语言-快速参考For more information about regular expressions, see .NET Framework Regular Expressions and Regular Expression Language - Quick Reference.

evaluator参数是你定义的用于检查每个匹配项的自定义方法的委托。The evaluator parameter is the delegate for a custom method that you define and that examines each match. 自定义方法必须具有以下签名才能匹配MatchEvaluator委托。The custom method must have the following signature to match the MatchEvaluator delegate.

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

自定义方法返回替换匹配输入的字符串。Your custom method returns a string that replaces the matched input.

RightToLeft 如果options为参数指定, 则搜索匹配项将从输入字符串的末尾开始, 并向左移动; 否则, 搜索将从输入字符串的开头开始向右移动。If you specify RightToLeft for the options parameter, the search for matches begins at the end of the input string and moves left; otherwise, the search begins at the start of the input string and moves right.

matchTimeout参数指定模式匹配方法在超时之前应尝试找到匹配项的时间长度。设置超时间隔可防止正则表达式依赖于过量回溯, 使其在处理包含接近匹配项的输入时停止响应。The matchTimeout parameter specifies how long a pattern matching method should try to find a match before it times out. Setting a time-out interval prevents regular expressions that rely on excessive backtracking from appearing to "stop responding when they process input that contains near matches. 有关详细信息, 请参阅正则表达式和回溯的最佳实践For more information, see Best Practices for Regular Expressions and Backtracking. 如果在该时间间隔内未找到匹配项, 则该方法RegexMatchTimeoutException将引发异常。If no match is found in that time interval, the method throws a RegexMatchTimeoutException exception. matchTimeout重写为在其中执行该方法的应用程序域定义的任何默认超时值。matchTimeout overrides any default time-out value defined for the application domain in which the method executes.

因为如果没有匹配input项, 则此方法返回不变, 你可以Object.ReferenceEquals使用方法来确定该方法是否已对输入字符串进行任何替换。Because the method returns input unchanged if there is no match, you can use the Object.ReferenceEquals method to determine whether the method has made any replacements to the input string.

调用方说明

建议将matchTimeout参数设置为适当的值, 例如两秒钟。We recommend that you set the matchTimeout parameter to an appropriate value, such as two seconds. 如果通过指定InfiniteMatchTimeout禁用超时, 则正则表达式引擎可提供略微更好的性能。If you disable time-outs by specifying InfiniteMatchTimeout, the regular expression engine offers slightly better performance. 但是, 只应在以下条件下禁用超时:However, you should disable time-outs only under the following conditions: -正则表达式处理的输入派生自已知的和受信任的源, 或由静态文本组成。- When the input processed by a regular expression is derived from a known and trusted source or consists of static text. 这不包括用户动态输入的文本。This excludes text that has been dynamically input by users.

-对正则表达式模式进行了全面测试, 以确保它有效地处理匹配、不匹配和接近匹配项。- When the regular expression pattern has been thoroughly tested to ensure that it efficiently handles matches, non-matches, and near matches.

-当正则表达式模式不包含已知的语言元素时, 这些元素会导致在处理接近的匹配时导致过度回溯。- When the regular expression pattern contains no language elements that are known to cause excessive backtracking when processing a near match.

另请参阅

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

在指定的输入字符串内,使用指定的替换字符串替换与指定正则表达式匹配的所有字符串。In a specified input string, replaces all strings that match a specified regular expression with a specified replacement string. 如果未找到匹配项,则其他参数指定修改匹配操作的选项和超时间隔。Additional parameters specify options that modify the matching operation and a time-out interval if no match is found.

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

参数

input
String String String String

要搜索匹配项的字符串。The string to search for a match.

pattern
String String String String

要匹配的正则表达式模式。The regular expression pattern to match.

replacement
String String String String

替换字符串。The replacement string.

options
RegexOptions RegexOptions RegexOptions RegexOptions

枚举值的一个按位组合,这些枚举值提供匹配选项。A bitwise combination of the enumeration values that provide options for matching.

matchTimeout
TimeSpan TimeSpan TimeSpan TimeSpan

超时间隔;若要指示该方法不应超时,则为 InfiniteMatchTimeoutA time-out interval, or InfiniteMatchTimeout to indicate that the method should not time out.

返回

一个与输入字符串基本相同的新字符串,唯一的差别在于,其中的每个匹配字符串已被替换字符串代替。A new string that is identical to the input string, except that the replacement string takes the place of each matched string. 如果 pattern 与当前实例不匹配,则此方法返回未更改的当前实例。If pattern is not matched in the current instance, the method returns the current instance unchanged.

异常

出现正则表达式分析错误。A regular expression parsing error occurred.

inputpatternreplacementnullinput, pattern, or replacement is null.

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

-or- matchTimeout 为负、零或大于 24 天左右。matchTimeout is negative, zero, or greater than approximately 24 days.

发生超时。A time-out occurred. 有关超时的详细信息,请参阅“备注”部分。For more information about time-outs, see the Remarks section.

示例

下面的示例使用Replace(String, String, String, RegexOptions, TimeSpan)方法将 UNC 路径中的本地计算机和驱动器名称替换为本地文件路径。The following example uses the Replace(String, String, String, RegexOptions, TimeSpan) method to replace the local machine and drive names in a UNC path with a local file path. 正则表达式使用Environment.MachineName属性包含本地计算机的名称Environment.GetLogicalDrives , 并使用方法来包含逻辑驱动器的名称。The regular expression uses the Environment.MachineName property to include the name of the local computer and the Environment.GetLogicalDrives method to include the names of the logical drives. 所有正则表达式字符串比较都不区分大小写, 并且如果在0.5 秒内找不到匹配项, 则任何单个替换操作都将超时。All regular expression string comparisons are case-insensitive, and any single replacement operation times out if a match cannot be found in 0.5 second. 若要成功运行此示例, 应将文本字符串 "MyMachine" 替换为本地计算机名称。To run the example successfully, you should replace the literal string "MyMachine" with your local machine name.

using System;
using System.Text.RegularExpressions;

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

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

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

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

正则表达式模式由以下表达式定义:The regular expression pattern is defined by the following expression:

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

下表演示了如何解释正则表达式模式。The following table shows how the regular expression pattern is interpreted.

模式Pattern 说明Description
\\\\ 匹配两个连续的\反斜杠 () 字符。\\\\
+ Environment.MachineName + Environment.MachineName属性返回的字符串匹配。Match the string that is returned by the Environment.MachineName property.
(?:\.\w+)* 匹配后跟一个.或多个单词字符的句点 () 字符。Match the period (.) character followed by one or more word characters. 此匹配可以出现零次或多次。This match can occur zero or more times. 不捕获匹配的子表达式。The matched subexpression is not captured.
\\ 匹配反斜杠 (\) 字符。\\
([" + driveNames + "]) 匹配由单个驱动器号组成的字符类。Match the character class that consists of the individual drive letters. 此匹配是第一个捕获的子表达式。This match is the first captured subexpression.
\$ 匹配文本美元符号 ($) 字符。Match the literal dollar sign ($) character.

替换模式$1将整个匹配项替换为第一个捕获的子表达式。The replacement pattern $1 replaces the entire match with the first captured subexpression. 也就是说, 它将 UNC 计算机和驱动器名称替换为驱动器号。That is, it replaces the UNC machine and drive name with the drive letter.

注解

静态Replace方法等效于使用指定的正Regex则表达式模式构造对象并调用实例方法ReplaceThe static Replace methods are equivalent to constructing a Regex object with the specified regular expression pattern and calling the instance method Replace.

pattern参数包含符号描述要匹配的字符串的正则表达式语言元素。The pattern parameter consists of regular expression language elements that symbolically describe the string to match. 有关正则表达式的详细信息, 请参阅.NET Framework 正则表达式正则表达式语言-快速参考For more information about regular expressions, see .NET Framework Regular Expressions and Regular Expression Language - Quick Reference. RightToLeft 如果options为参数指定, 则搜索匹配项将从输入字符串的末尾开始, 并向左移动; 否则, 搜索将从输入字符串的开头开始向右移动。If you specify RightToLeft for the options parameter, the search for matches begins at the end of the input string and moves left; otherwise, the search begins at the start of the input string and moves right.

参数指定要在input其中替换每个匹配项的字符串。 replacementThe replacement parameter specifies the string that is to replace each match in input. replacement可以包含文字文本和替换的任意组合。replacement can consist of any combination of literal text and substitutions. 例如, 替换模式a*${test}b插入字符串 "a *", 后面跟有test捕获组匹配的子字符串 (如果有), 后跟字符串 "b"。For example, the replacement pattern a*${test}b inserts the string "a*" followed by the substring that is matched by the test capturing group, if any, followed by the string "b". 在替换模式中不将 * 字符识别为元字符。The * character is not recognized as a metacharacter within a replacement pattern.

备注

替换是替换模式中唯一识别的正则表达式语言元素。Substitutions are the only regular expression language elements that are recognized in a replacement pattern. 所有其他正则表达式语言元素 (包括字符转义) 仅在正则表达式模式中允许, 在替换模式下不能识别。All other regular expression language elements, including character escapes, are allowed in regular expression patterns only and are not recognized in replacement patterns.

matchTimeout参数指定模式匹配方法在超时之前应尝试找到匹配项的时间长度。设置超时间隔可防止正则表达式在处理包含接近匹配项的输入时, 这些表达式会出现依赖于过量回溯的正则表达式停止响应。The matchTimeout parameter specifies how long a pattern matching method should try to find a match before it times out. Setting a time-out interval prevents regular expressions that rely on excessive backtracking from appearing to stop responding when they process input that contains near matches. 有关详细信息, 请参阅正则表达式和回溯的最佳实践For more information, see Best Practices for Regular Expressions and Backtracking. 如果在该时间间隔内未找到匹配项, 则该方法RegexMatchTimeoutException将引发异常。If no match is found in that time interval, the method throws a RegexMatchTimeoutException exception. matchTimeout重写为在其中执行该方法的应用程序域定义的任何默认超时值。matchTimeout overrides any default time-out value defined for the application domain in which the method executes.

因为如果没有匹配input项, 则此方法返回不变, 你可以Object.ReferenceEquals使用方法来确定该方法是否已对输入字符串进行任何替换。Because the method returns input unchanged if there is no match, you can use the Object.ReferenceEquals method to determine whether the method has made any replacements to the input string.

调用方说明

建议将matchTimeout参数设置为适当的值, 例如两秒钟。We recommend that you set the matchTimeout parameter to an appropriate value, such as two seconds. 如果通过指定InfiniteMatchTimeout禁用超时, 则正则表达式引擎可提供略微更好的性能。If you disable time-outs by specifying InfiniteMatchTimeout, the regular expression engine offers slightly better performance. 但是, 只应在以下条件下禁用超时:However, you should disable time-outs only under the following conditions: -正则表达式处理的输入派生自已知的和受信任的源, 或由静态文本组成。- When the input processed by a regular expression is derived from a known and trusted source or consists of static text. 这不包括用户动态输入的文本。This excludes text that has been dynamically input by users.

-对正则表达式模式进行了全面测试, 以确保它有效地处理匹配、不匹配和接近匹配项。- When the regular expression pattern has been thoroughly tested to ensure that it efficiently handles matches, non-matches, and near matches.

-当正则表达式模式不包含已知的语言元素时, 这些元素会导致在处理接近的匹配时导致过度回溯。- When the regular expression pattern contains no language elements that are known to cause excessive backtracking when processing a near match.

另请参阅

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

在指定的输入子字符串内,使用 MatchEvaluator 委托返回的字符串替换与某个正则表达式模式匹配的字符串(其数目为指定的最大数目)。In a specified input substring, replaces a specified maximum number of strings that match a regular expression pattern with a string returned by a MatchEvaluator delegate.

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

参数

input
String String String String

要搜索匹配项的字符串。The string to search for a match.

evaluator
MatchEvaluator MatchEvaluator MatchEvaluator MatchEvaluator

一个自定义方法,该方法检查每个匹配项,然后返回原始的匹配字符串或替换字符串。A custom method that examines each match and returns either the original matched string or a replacement string.

count
Int32 Int32 Int32 Int32

进行替换的最大次数。The maximum number of times the replacement will occur.

startat
Int32 Int32 Int32 Int32

输入字符串中开始执行搜索的字符位置。The character position in the input string where the search begins.

返回

一个与输入字符串基本相同的新字符串,唯一的差别在于,其中的每个匹配字符串已被一个替换字符串代替。A new string that is identical to the input string, except that a replacement string takes the place of each matched string. 如果正则表达式模式与当前实例不匹配,则此方法返回未更改的当前实例。If the regular expression pattern is not matched in the current instance, the method returns the current instance unchanged.

异常

inputevaluatornullinput or evaluator is null.

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

发生超时。A time-out occurred. 有关超时的详细信息,请参阅“备注”部分。For more information about time-outs, see the Remarks section.

注解

如果满足以下任一条件, 则方法可用于替换正则表达式匹配:Regex.Replace(String, MatchEvaluator, Int32, Int32)The Regex.Replace(String, MatchEvaluator, Int32, Int32) method is useful for replacing a regular expression match if any of the following conditions is true:

  • 正则表达式替换模式无法轻易指定替换字符串。The replacement string cannot readily be specified by a regular expression replacement pattern.

  • 替换字符串是对匹配的字符串执行的一些处理导致的。The replacement string results from some processing done on the matched string.

  • 从条件处理中得到的替换字符串。The replacement string results from conditional processing.

方法等效于Regex.Matches(String, Int32)调用方法, 并将返回MatchCollection集合中的count第一个Match对象传递到evaluator委托。The method is equivalent to calling the Regex.Matches(String, Int32) method and passing the first countMatch objects in the returned MatchCollection collection to the evaluator delegate.

正则表达式是由当前Regex对象的构造函数定义的模式。The regular expression is the pattern defined by the constructor for the current Regex object.

evaluator参数是你定义的用于检查每个匹配项的自定义方法的委托。The evaluator parameter is the delegate for a custom method that you define and that examines each match. 自定义方法必须具有以下签名才能匹配MatchEvaluator委托。The custom method must have the following signature to match the MatchEvaluator delegate.

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

自定义方法返回替换匹配输入的字符串。Your custom method returns a string that replaces the matched input.

如果替换操作的执行时间超过了Regex.Regex(String, RegexOptions, TimeSpan)构造函数指定的超时间隔, 则会引发异常。RegexMatchTimeoutExceptionThe 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将返回集合中的每个对象传递给委托。evaluatorThe method is equivalent to calling the Regex.Matches(String, String, RegexOptions) method and passing each Match object in the returned MatchCollection collection to the evaluator delegate.

pattern参数包含符号描述要匹配的字符串的正则表达式语言元素。The pattern parameter consists of regular expression language elements that symbolically describe the string to match. 有关正则表达式的详细信息, 请参阅.NET Framework 正则表达式正则表达式语言-快速参考For more information about regular expressions, see .NET Framework Regular Expressions and Regular Expression Language - Quick Reference.

evaluator参数是你定义的用于检查每个匹配项的自定义方法的委托。The evaluator parameter is the delegate for a custom method that you define and that examines each match. 自定义方法必须具有以下签名才能匹配MatchEvaluator委托。The custom method must have the following signature to match the MatchEvaluator delegate.

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

自定义方法返回替换匹配输入的字符串。Your custom method returns a string that replaces the matched input.

RightToLeft 如果options为参数指定, 则搜索匹配项将从输入字符串的末尾开始, 并向左移动; 否则, 搜索将从输入字符串的开头开始向右移动。If you specify RightToLeft for the options parameter, the search for matches begins at the end of the input string and moves left; otherwise, the search begins at the start of the input string and moves right.

如果替换操作的执行时间超过为其调用该方法的应用程序域指定的超时间隔, 则会引发异常。RegexMatchTimeoutExceptionThe RegexMatchTimeoutException exception is thrown if the execution time of the replacement operation exceeds the time-out interval specified for the application domain in which the method is called. 如果在应用程序域的属性中没有定义超时, 或者超时值为Regex.InfiniteMatchTimeout, 则不会引发异常。If no time-out is defined in the application domain's properties, or if the time-out value is Regex.InfiniteMatchTimeout, no exception is thrown.

因为如果没有匹配input项, 则此方法返回不变, 你可以Object.ReferenceEquals使用方法来确定该方法是否已对输入字符串进行任何替换。Because the method returns input unchanged if there is no match, you can use the Object.ReferenceEquals method to determine whether the method has made any replacements to the input string.

另请参阅

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

在指定输入子字符串内,使用指定替换字符串替换与某个正则表达式模式匹配的字符串(其数目为指定的最大数目)。In a specified input substring, replaces a specified maximum number of strings that match a regular expression pattern with a specified replacement string.

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

参数

input
String String String String

要搜索匹配项的字符串。The string to search for a match.

replacement
String String String String

替换字符串。The replacement string.

count
Int32 Int32 Int32 Int32

可进行替换的最大次数。Maximum number of times the replacement can occur.

startat
Int32 Int32 Int32 Int32

输入字符串中开始执行搜索的字符位置。The character position in the input string where the search begins.

返回

一个与输入字符串基本相同的新字符串,唯一的差别在于,其中的每个匹配字符串已被替换字符串代替。A new string that is identical to the input string, except that the replacement string takes the place of each matched string. 如果正则表达式模式与当前实例不匹配,则此方法返回未更改的当前实例。If the regular expression pattern is not matched in the current instance, the method returns the current instance unchanged.

异常

inputreplacementnullinput or replacement is null.

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

发生超时。A time-out occurred. 有关超时的详细信息,请参阅“备注”部分。For more information about time-outs, see the Remarks section.

示例

下面的示例在字符串的第一行之外的所有字符都是双空格。The following example double-spaces all but the first line of a string. 它定义了与文本行匹配^.*$的正则表达式模式, Match(String)调用方法与Match.Index字符串的第一行匹配, 并使用和Match.Count属性来确定第二个的起始位置内嵌.It defines a regular expression pattern, ^.*$, that matches a line of text, calls the Match(String) method to match the first line of the string, and uses the Match.Index and Match.Count properties to determine the starting position of the second line.

using System;
using System.Text.RegularExpressions;

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

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

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

正则表达式模式 ^.*$ 的定义如下表所示。The regular expression pattern ^.*$ is defined as shown in the following table.

模式Pattern 说明Description
^ 匹配行的开头。Match the start of a line. (请注意, RegexRegexOptions.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. (请注意, RegexRegexOptions.Multiline使用选项对对象进行实例化; 否则, 此字符类将仅与输入字符串的开头匹配。)(Note that the Regex object was instantiated by using the RegexOptions.Multiline option; otherwise, this character class would only match the beginning of the input string.)

替换字符串 (vbCrLf + "$&"在中为"\n$&" Visual Basic) C#在匹配的字符串之前添加新行。The replacement string (vbCrLf + "$&" in Visual Basic, "\n$&" in C#) adds a new line before the matched string. 请注意\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.

参数指定要在input其中替换每个匹配项的字符串。 replacementThe replacement parameter specifies the string that is to replace each match in input. replacement可以包含文字文本和替换的任意组合。replacement can consist of any combination of literal text and substitutions. 例如, 替换模式a*${test}b插入字符串 "a *", 后面跟有test捕获组匹配的子字符串 (如果有), 后跟字符串 "b"。For example, the replacement pattern a*${test}b inserts the string "a*" followed by the substring that is matched by the test capturing group, if any, followed by the string "b". 在替换模式中不将 * 字符识别为元字符。The * character is not recognized as a metacharacter within a replacement pattern.

备注

替换是替换模式中唯一识别的正则表达式语言元素。Substitutions are the only regular expression language elements that are recognized in a replacement pattern. 所有其他正则表达式语言元素 (包括字符转义) 仅在正则表达式模式中允许, 在替换模式下不能识别。All other regular expression language elements, including character escapes, are allowed in regular expression patterns only and are not recognized in replacement patterns.

如果替换操作的执行时间超过了Regex.Regex(String, RegexOptions, TimeSpan)构造函数指定的超时间隔, 则会引发异常。RegexMatchTimeoutExceptionThe RegexMatchTimeoutException exception is thrown if the execution time of the replacement operation exceeds the time-out interval specified by the Regex.Regex(String, RegexOptions, TimeSpan) constructor. 如果在调用构造函数时未设置超时间隔, 则当操作超过在其中Regex创建对象的应用程序域的任何超时值时, 将引发异常。If you do not set a time-out interval when you call the constructor, the exception is thrown if the operation exceeds any time-out value established for the application domain in which the Regex object is created. 如果在Regex构造函数调用或应用程序域的属性中没有定义超时, 或者超时值为Regex.InfiniteMatchTimeout, 则不会引发异常If no time-out is defined in the Regex constructor call or in the application domain's properties, or if the time-out value is Regex.InfiniteMatchTimeout, no exception is thrown

因为如果没有匹配input项, 则此方法返回不变, 你可以Object.ReferenceEquals使用方法来确定该方法是否已对输入字符串进行任何替换。Because the method returns input unchanged if there is no match, you can use the Object.ReferenceEquals method to determine whether the method has made any replacements to the input string.

另请参阅

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

在指定的输入字符串内,使用指定的替换字符串替换与指定正则表达式匹配的所有字符串。In a specified input string, replaces all strings that match a specified regular expression with a specified replacement string. 指定的选项将修改匹配操作。Specified options modify the matching operation.

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

参数

input
String String String String

要搜索匹配项的字符串。The string to search for a match.

pattern
String String String String

要匹配的正则表达式模式。The regular expression pattern to match.

replacement
String String String String

替换字符串。The replacement string.

options
RegexOptions RegexOptions RegexOptions RegexOptions

枚举值的一个按位组合,这些枚举值提供匹配选项。A bitwise combination of the enumeration values that provide options for matching.

返回

一个与输入字符串基本相同的新字符串,唯一的差别在于,其中的每个匹配字符串已被替换字符串代替。A new string that is identical to the input string, except that the replacement string takes the place of each matched string. 如果 pattern 与当前实例不匹配,则此方法返回未更改的当前实例。If pattern is not matched in the current instance, the method returns the current instance unchanged.

异常

出现正则表达式分析错误。A regular expression parsing error occurred.

inputpatternreplacementnullinput, pattern, or replacement is null.

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

发生超时。A time-out occurred. 有关超时的详细信息,请参阅“备注”部分。For more information about time-outs, see the Remarks section.

示例

下面的示例使用Replace(String, String, String, RegexOptions)方法将 UNC 路径中的本地计算机和驱动器名称替换为本地文件路径。The following example uses the Replace(String, String, String, RegexOptions) method to replace the local machine and drive names in a UNC path with a local file path. 正则表达式使用Environment.MachineName属性包含本地计算机的名称, Environment.GetLogicalDrives并使用方法来包含逻辑驱动器的名称。The regular expression uses the Environment.MachineName property to include the name of the local computer, and the Environment.GetLogicalDrives method to include the names of the logical drives. 所有正则表达式字符串比较都不区分大小写。All regular expression string comparisons are case-insensitive. 若要成功运行此示例, 应将文本字符串 "MyMachine" 替换为本地计算机名称。To run the example successfully, you should replace the literal string "MyMachine" with your local machine name.

using System;
using System.Text.RegularExpressions;

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

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

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

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

正则表达式模式由以下表达式定义:The regular expression pattern is defined by the following expression:

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

下表演示了如何解释正则表达式模式。The following table shows how the regular expression pattern is interpreted.

模式Pattern 说明Description
\\\\ 匹配两个连续的\反斜杠 () 字符。\\\\
+ Environment.MachineName + Environment.MachineName属性返回的字符串匹配。Match the string that is returned by the Environment.MachineName property.
(?:\.\w+)* 匹配后跟一个.或多个单词字符的句点 () 字符。Match the period (.) character followed by one or more word characters. 此匹配可以出现零次或多次。This match can occur zero or more times. 不捕获匹配的子表达式。The matched subexpression is not captured.
\\ 匹配反斜杠 (\) 字符。\\
([" + driveNames + "]) 匹配由单个驱动器号组成的字符类。Match the character class that consists of the individual drive letters. 此匹配是第一个捕获的子表达式。This match is the first captured subexpression.
\$ 匹配文本美元符号 ($) 字符。Match the literal dollar sign ($) character.

替换模式$1将整个匹配项替换为第一个捕获的子表达式。The replacement pattern $1 replaces the entire match with the first captured subexpression. 也就是说, 它将 UNC 计算机和驱动器名称替换为驱动器号。That is, it replaces the UNC machine and drive name with the drive letter.

注解

静态Replace方法等效于使用指定的正Regex则表达式模式构造对象并调用实例方法ReplaceThe static Replace methods are equivalent to constructing a Regex object with the specified regular expression pattern and calling the instance method Replace.

pattern参数包含符号描述要匹配的字符串的正则表达式语言元素。The pattern parameter consists of regular expression language elements that symbolically describe the string to match. 有关正则表达式的详细信息, 请参阅.NET Framework 正则表达式正则表达式语言-快速参考For more information about regular expressions, see .NET Framework Regular Expressions and Regular Expression Language - Quick Reference. RightToLeft 如果options为参数指定, 则搜索匹配项将从输入字符串的末尾开始, 并向左移动; 否则, 搜索将从输入字符串的开头开始向右移动。If you specify RightToLeft for the options parameter, the search for matches begins at the end of the input string and moves left; otherwise, the search begins at the start of the input string and moves right.

参数指定要在input其中替换每个匹配项的字符串。 replacementThe replacement parameter specifies the string that is to replace each match in input. replacement可以包含文字文本和替换的任意组合。replacement can consist of any combination of literal text and substitutions. 例如, 替换模式a*${test}b插入字符串 "a *", 后面跟有test捕获组匹配的子字符串 (如果有), 后跟字符串 "b"。For example, the replacement pattern a*${test}b inserts the string "a*" followed by the substring that is matched by the test capturing group, if any, followed by the string "b". 在替换模式中不将 * 字符识别为元字符。The * character is not recognized as a metacharacter within a replacement pattern.

备注

替换是替换模式中唯一识别的正则表达式语言元素。Substitutions are the only regular expression language elements that are recognized in a replacement pattern. 所有其他正则表达式语言元素 (包括字符转义) 仅在正则表达式模式中允许, 在替换模式下不能识别。All other regular expression language elements, including character escapes, are allowed in regular expression patterns only and are not recognized in replacement patterns.

如果替换操作的执行时间超过为其调用该方法的应用程序域指定的超时间隔, 则会引发异常。RegexMatchTimeoutExceptionThe 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将返回集合中的每个对象传递给委托。evaluatorThe 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.

如果替换操作的执行时间超过为其调用该方法的应用程序域指定的超时间隔, 则会引发异常。RegexMatchTimeoutExceptionThe RegexMatchTimeoutException exception is thrown if the execution time of the replacement operation exceeds the time-out interval specified for the application domain in which the method is called. 如果在应用程序域的属性中没有定义超时, 或者超时值为Regex.InfiniteMatchTimeout, 则不会引发异常。If no time-out is defined in the application domain's properties, or if the time-out value is Regex.InfiniteMatchTimeout, no exception is thrown.

因为如果没有匹配input项, 则此方法返回不变, 你可以Object.ReferenceEquals使用方法来确定该方法是否已对输入字符串进行任何替换。Because the method returns input unchanged if there is no match, you can use the Object.ReferenceEquals method to determine whether the method has made any replacements to the input string.

调用方说明

此方法在与调用该方法的应用程序域的默认超时值相等的时间间隔后超时。This method times out after an interval that is equal to the default time-out value of the application domain in which it is called. 如果尚未为应用程序域定义超时值, 则将使用该值InfiniteMatchTimeout来阻止方法超时。If a time-out value has not been defined for the application domain, the value InfiniteMatchTimeout, which prevents the method from timing out, is used. 用于计算和替换模式匹配的推荐静态方法是Replace(String, String, MatchEvaluator, RegexOptions, TimeSpan), 这使你可以设置超时间隔。The recommended static method for evaluating and replacing a pattern match is Replace(String, String, MatchEvaluator, RegexOptions, TimeSpan), which lets you set the time-out interval.

另请参阅

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

在指定的输入字符串内,使用指定的替换字符串替换与指定正则表达式匹配的所有字符串。In a specified input string, replaces all strings that match a specified regular expression with a specified replacement string.

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

参数

input
String String String String

要搜索匹配项的字符串。The string to search for a match.

pattern
String String String String

要匹配的正则表达式模式。The regular expression pattern to match.

replacement
String String String String

替换字符串。The replacement string.

返回

一个与输入字符串基本相同的新字符串,唯一的差别在于,其中的每个匹配字符串已被替换字符串代替。A new string that is identical to the input string, except that the replacement string takes the place of each matched string. 如果 pattern 与当前实例不匹配,则此方法返回未更改的当前实例。If pattern is not matched in the current instance, the method returns the current instance unchanged.

异常

出现正则表达式分析错误。A regular expression parsing error occurred.

inputpatternreplacementnullinput, pattern, or replacement is null.

发生超时。A time-out occurred. 有关超时的详细信息,请参阅“备注”部分。For more information about time-outs, see the Remarks section.

示例

下面的示例定义了一个与一个\s+或多个空白字符匹配的正则表达式。The following example defines a regular expression, \s+, that matches one or more white-space characters. 替换字符串 "" 会将它们替换为单个空格字符。The replacement string, " ", replaces them with a single space character.

using System;
using System.Text.RegularExpressions;

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

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

下面的示例使用Replace(String, String, String)方法将 UNC 路径中的本地计算机和驱动器名称替换为本地文件路径。The following example uses the Replace(String, String, String) method to replace the local machine and drive names in a UNC path with a local file path. 正则表达式使用Environment.MachineName属性包含本地计算机的名称, Environment.GetLogicalDrives并使用方法来包含逻辑驱动器的名称。The regular expression uses the Environment.MachineName property to include the name of the local computer, and the Environment.GetLogicalDrives method to include the names of the logical drives. 若要成功运行此示例, 应将文本字符串 "MyMachine" 替换为本地计算机名称。To run the example successfully, you should replace the literal string "MyMachine" with your local machine name.

using System;
using System.Text.RegularExpressions;

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

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

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

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

正则表达式模式由以下表达式定义:The regular expression pattern is defined by the following expression:

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

下表演示了如何解释正则表达式模式。The following table shows how the regular expression pattern is interpreted.

模式Pattern 说明Description
\\\\ 匹配两个连续的\反斜杠 () 字符。\\\\
(?i:" + Environment.MachineName + ") 执行Environment.MachineName属性返回的字符串的不区分大小写的匹配项。Perform a case-insensitive match of the string that is returned by the Environment.MachineName property.
(?:\.\w+)* 匹配后跟一个.或多个单词字符的句点 () 字符。Match the period (.) character followed by one or more word characters. 此匹配可以出现零次或多次。This match can occur zero or more times. 不捕获匹配的子表达式。The matched subexpression is not captured.
\\ 匹配反斜杠 (\) 字符。\\
((?i:[" + driveNames + "])) 执行由单个驱动器号组成的字符类的不区分大小写的匹配项。Perform a case-insensitive match of the character class that consists of the individual drive letters. 此匹配是第一个捕获的子表达式。This match is the first captured subexpression.
\$ 匹配文本美元符号 ($) 字符。Match the literal dollar sign ($) character.

替换模式$1将整个匹配项替换为第一个捕获的子表达式。The replacement pattern $1 replaces the entire match with the first captured subexpression. 也就是说, 它将 UNC 计算机和驱动器名称替换为驱动器号。That is, it replaces the UNC machine and drive name with the drive letter.

注解

静态Replace方法等效于使用指定的正Regex则表达式模式构造对象并调用实例方法ReplaceThe static Replace methods are equivalent to constructing a Regex object with the specified regular expression pattern and calling the instance method Replace.

pattern参数包含符号描述要匹配的字符串的正则表达式语言元素。The pattern parameter consists of regular expression language elements that symbolically describe the string to match. 有关正则表达式的详细信息, 请参阅.NET Framework 正则表达式正则表达式语言-快速参考For more information about regular expressions, see .NET Framework Regular Expressions and Regular Expression Language - Quick Reference. 搜索匹配项从input字符串的开头开始。The search for matches starts at the beginning of the input string.

参数指定要在input其中替换每个匹配项的字符串。 replacementThe replacement parameter specifies the string that is to replace each match in input. replacement可以包含文字文本和替换的任意组合。replacement can consist of any combination of literal text and substitutions. 例如, 替换模式a*${test}b插入字符串 "a *", 后面跟有test捕获组匹配的子字符串 (如果有), 后跟字符串 "b"。For example, the replacement pattern a*${test}b inserts the string "a*" followed by the substring that is matched by the test capturing group, if any, followed by the string "b". 在替换模式中不将 * 字符识别为元字符。The * character is not recognized as a metacharacter within a replacement pattern.

备注

替换是替换模式中唯一识别的正则表达式语言元素。Substitutions are the only regular expression language elements that are recognized in a replacement pattern. 所有其他正则表达式语言元素 (包括字符转义) 仅在正则表达式模式中允许, 在替换模式下不能识别。All other regular expression language elements, including character escapes, are allowed in regular expression patterns only and are not recognized in replacement patterns.

如果替换操作的执行时间超过为其调用该方法的应用程序域指定的超时间隔, 则会引发异常。RegexMatchTimeoutExceptionThe RegexMatchTimeoutException exception is thrown if the execution time of the replacement operation exceeds the time-out interval specified for the application domain in which the method is called. 如果在应用程序域的属性中没有定义超时, 或者超时值为Regex.InfiniteMatchTimeout, 则不会引发异常。If no time-out is defined in the application domain's properties, or if the time-out value is Regex.InfiniteMatchTimeout, no exception is thrown.

因为如果没有匹配input项, 则此方法返回不变, 你可以Object.ReferenceEquals使用方法来确定该方法是否已对输入字符串进行任何替换。Because the method returns input unchanged if there is no match, you can use the Object.ReferenceEquals method to determine whether the method has made any replacements to the input string.

调用方说明

此方法在与调用该方法的应用程序域的默认超时值相等的时间间隔后超时。This method times out after an interval that is equal to the default time-out value of the application domain in which it is called. 如果尚未为应用程序域定义超时值, 则将使用该值InfiniteMatchTimeout来阻止方法超时。If a time-out value has not been defined for the application domain, the value InfiniteMatchTimeout, which prevents the method from timing out, is used. 建议用于替换模式匹配的静态方法是Replace(String, String, String, RegexOptions, TimeSpan), 这使你可以设置超时间隔。The recommended static method for replacing a pattern match is Replace(String, String, String, RegexOptions, TimeSpan), which lets you set the time-out interval.

另请参阅

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

在指定输入字符串内,使用指定替换字符串替换与某个正则表达式模式匹配的字符串(其数目为指定的最大数目)。In a specified input string, replaces a specified maximum number of strings that match a regular expression pattern with a specified replacement string.

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

参数

input
String String String String

要搜索匹配项的字符串。The string to search for a match.

replacement
String String String String

替换字符串。The replacement string.

count
Int32 Int32 Int32 Int32

可进行替换的最大次数。The maximum number of times the replacement can occur.

返回

一个与输入字符串基本相同的新字符串,唯一的差别在于,其中的每个匹配字符串已被替换字符串代替。A new string that is identical to the input string, except that the replacement string takes the place of each matched string. 如果正则表达式模式与当前实例不匹配,则此方法返回未更改的当前实例。If the regular expression pattern is not matched in the current instance, the method returns the current instance unchanged.

异常

inputreplacementnullinput or replacement is null.

发生超时。A time-out occurred. 有关超时的详细信息,请参阅“备注”部分。For more information about time-outs, see the Remarks section.

示例

下面的示例将重复字符的前五个匹配项替换为单个字符。The following example replaces the first five occurrences of duplicated characters with a single character. 正则表达式模式(\w)\1匹配单个字符连续出现的次数, 并将第一个匹配项赋给第一个捕获组。The regular expression pattern (\w)\1 matches consecutive occurrences of a single character and assigns the first occurrence to the first capturing group. 替换模式$1会将整个匹配项替换为第一个捕获的组。The replacement pattern $1 replaces the entire match with the first captured group.

using System;
using System.Text.RegularExpressions;

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

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

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

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

注解

搜索匹配项从input字符串的开头开始。The search for matches starts at the beginning of the input string. 正则表达式是由当前Regex对象的构造函数定义的模式。The regular expression is the pattern that is defined by the constructor for the current Regex object. 如果count为负, 则替换将继续到字符串的末尾。If count is negative, replacements continue to the end of the string. 如果count超过匹配项的数目, 则将替换所有匹配项。If count exceeds the number of matches, all matches are replaced.

参数指定要替换中input第一个count匹配项的字符串。 replacementThe replacement parameter specifies the string that is to replace the first count matches in input. replacement可以包含文字文本和替换的任意组合。replacement can consist of any combination of literal text and substitutions. 例如, 替换模式a*${test}b插入字符串 "a *", 后面跟有test捕获组匹配的子字符串 (如果有), 后跟字符串 "b"。For example, the replacement pattern a*${test}b inserts the string "a*" followed by the substring that is matched by the test capturing group, if any, followed by the string "b". 在替换模式中不将 * 字符识别为元字符。The * character is not recognized as a metacharacter within a replacement pattern.

备注

替换是替换模式中唯一识别的正则表达式语言元素。Substitutions are the only regular expression language elements that are recognized in a replacement pattern. 所有其他正则表达式语言元素 (包括字符转义) 仅在正则表达式模式中允许, 在替换模式下不能识别。All other regular expression language elements, including character escapes, are allowed in regular expression patterns only and are not recognized in replacement patterns.

如果替换操作的执行时间超过了Regex.Regex(String, RegexOptions, TimeSpan)构造函数指定的超时间隔, 则会引发异常。RegexMatchTimeoutExceptionThe 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将返回集合中的每个对象传递给委托。evaluatorThe 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.

如果替换操作的执行时间超过了Regex.Regex(String, RegexOptions, TimeSpan)构造函数指定的超时间隔, 则会引发异常。RegexMatchTimeoutExceptionThe 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.

参数指定要在input其中替换每个匹配项的字符串。 replacementThe replacement parameter specifies the string that is to replace each match in input. replacement可以包含文字文本和替换的任意组合。replacement can consist of any combination of literal text and substitutions. 例如, 替换模式a*${test}b插入字符串 "a *", 后面跟有test捕获组匹配的子字符串 (如果有), 后跟字符串 "b"。For example, the replacement pattern a*${test}b inserts the string "a*" followed by the substring that is matched by the test capturing group, if any, followed by the string "b". 在替换模式中不将 * 字符识别为元字符。The * character is not recognized as a metacharacter within a replacement pattern.

备注

替换是替换模式中唯一识别的正则表达式语言元素。Substitutions are the only regular expression language elements that are recognized in a replacement pattern. 所有其他正则表达式语言元素 (包括字符转义) 仅在正则表达式模式中允许, 在替换模式下不能识别。All other regular expression language elements, including character escapes, are allowed in regular expression patterns only and are not recognized in replacement patterns.

如果替换操作的执行时间超过了Regex.Regex(String, RegexOptions, TimeSpan)构造函数指定的超时间隔, 则会引发异常。RegexMatchTimeoutExceptionThe RegexMatchTimeoutException exception is thrown if the execution time of the replacement operation exceeds the time-out interval specified by the Regex.Regex(String, RegexOptions, TimeSpan) constructor. 如果在调用构造函数时未设置超时间隔, 则当操作超过在其中Regex创建对象的应用程序域的任何超时值时, 将引发异常。If you do not set a time-out interval when you call the constructor, the exception is thrown if the operation exceeds any time-out value established for the application domain in which the Regex object is created. 如果在Regex构造函数调用或应用程序域的属性中没有定义超时, 或者超时值为Regex.InfiniteMatchTimeout, 则不会引发异常If no time-out is defined in the Regex constructor call or in the application domain's properties, or if the time-out value is Regex.InfiniteMatchTimeout, no exception is thrown

因为如果没有匹配input项, 则此方法返回不变, 你可以Object.ReferenceEquals使用方法来确定该方法是否已对输入字符串进行任何替换。Because the method returns input unchanged if there is no match, you can use the Object.ReferenceEquals method to determine whether the method has made any replacements to the input string.

另请参阅

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

在指定的输入字符串内,使用 MatchEvaluator 委托返回的字符串替换与某个正则表达式模式匹配的字符串(其数目为指定的最大数目)。In a specified input string, replaces a specified maximum number of strings that match a regular expression pattern with a string returned by a MatchEvaluator delegate.

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

参数

input
String String String String

要搜索匹配项的字符串。The string to search for a match.

evaluator
MatchEvaluator MatchEvaluator MatchEvaluator MatchEvaluator

一个自定义方法,该方法检查每个匹配项,然后返回原始的匹配字符串或替换字符串。A custom method that examines each match and returns either the original matched string or a replacement string.

count
Int32 Int32 Int32 Int32

进行替换的最大次数。The maximum number of times the replacement will occur.

返回

一个与输入字符串基本相同的新字符串,唯一的差别在于,其中的每个匹配字符串已被一个替换字符串代替。A new string that is identical to the input string, except that a replacement string takes the place of each matched string. 如果正则表达式模式与当前实例不匹配,则此方法返回未更改的当前实例。If the regular expression pattern is not matched in the current instance, the method returns the current instance unchanged.

异常

inputevaluatornullinput or evaluator is null.

发生超时。A time-out occurred. 有关超时的详细信息,请参阅“备注”部分。For more information about time-outs, see the Remarks section.

示例

下面的示例使用正则表达式来特意拼错列表中的半个单词。The following example uses a regular expression to deliberately misspell half of the words in a list. 它使用正则表达式\w*(ie|ei)\w*来匹配包含字符 "ie" 或 "ei" 的单词。It uses the regular expression \w*(ie|ei)\w* to match words that include the characters "ie" or "ei". 它将匹配单词的前半部分传递给ReverseLetter方法, 该方法反过来Replace(String, String, String, RegexOptions)使用方法反转匹配字符串中的 "i" 和 "e"。It passes the first half of the matching words to the ReverseLetter method, which, in turn, uses the Replace(String, String, String, RegexOptions) method to reverse "i" and "e" in the matched string. 其余单词保持不变。The remaining words remain unchanged.

using System;
using System.Text.RegularExpressions;

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

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

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

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

正则表达式 \w*(ie|ei)\w* 的定义如下表所示。The regular expression \w*(ie|ei)\w* is defined as shown in the following table.

模式Pattern 说明Description
\w* 匹配零个或多个单词字符。Match zero or more word characters.
(ie|ei) 匹配 "ie" 或 "ei"。Match either "ie" or "ei".
\w* 匹配零个或多个单词字符。Match zero or more word characters.

方法中的正([ie])([ie])则表达式模式匹配 diphthong "ie" 或 "ei" 中的第一个 "i" 或 "e", 并将该字母分配给第一个捕获组。 ReverseLetterThe regular expression pattern ([ie])([ie]) in the ReverseLetter method matches the first "i" or "e" in the diphthong "ie" or "ei" and assigns the letter to the first capturing group. 它与第二个 "i" 或 "e" 匹配, 并将该字母分配给第二个捕获组。It matches the second "i" or "e" and assigns the letter to the second capturing group. 然后通过使用替换模式Replace(String, String, String) $2$1调用方法来反转两个字符。The two characters are then reversed by calling the Replace(String, String, String) method with the replacement pattern $2$1.

注解

如果满足以下任一条件, 则方法可用于替换正则表达式匹配:Regex.Replace(String, MatchEvaluator, Int32)The Regex.Replace(String, MatchEvaluator, Int32) method is useful for replacing a regular expression match if any of the following conditions is true:

  • 正则表达式替换模式无法轻易指定替换字符串。The replacement string cannot readily be specified by a regular expression replacement pattern.

  • 替换字符串是对匹配的字符串执行的一些处理导致的。The replacement string results from some processing done on the matched string.

  • 从条件处理中得到的替换字符串。The replacement string results from conditional processing.

方法等效于Regex.Matches(String)调用方法, 并将返回MatchCollection集合中的count第一个Match对象传递到evaluator委托。The method is equivalent to calling the Regex.Matches(String) method and passing the first countMatch objects in the returned MatchCollection collection to the evaluator delegate.

正则表达式是由当前Regex对象的构造函数定义的模式。The regular expression is the pattern defined by the constructor for the current Regex object.

evaluator参数是你定义的用于检查每个匹配项的自定义方法的委托。The evaluator parameter is the delegate for a custom method that you define and that examines each match. 自定义方法必须具有以下签名才能匹配MatchEvaluator委托。The custom method must have the following signature to match the MatchEvaluator delegate.

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

自定义方法返回替换匹配输入的字符串。Your custom method returns a string that replaces the matched input.

如果替换操作的执行时间超过了Regex.Regex(String, RegexOptions, TimeSpan)构造函数指定的超时间隔, 则会引发异常。RegexMatchTimeoutExceptionThe 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.

另请参阅

适用于