Regex.Replace 方法

定义

在指定的输入字符串中,将匹配正则表达式模式的字符串替换为指定的替换字符串。

重载

Replace(String, MatchEvaluator, Int32, Int32)

在指定的输入子字符串中,用由 MatchEvaluator 委托返回的字符串替换与正则表达式模式匹配的指定最大字符串数。

Replace(String, String, String)

在指定的输入字符串中,将匹配指定正则表达式的所有字符串替换为指定的替换字符串。

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

在指定的输入字符串中,将匹配指定正则表达式的所有子字符串替换为由 MatchEvaluator 委托返回的字符串。 其他参数指定修改匹配操作的选项,如果未找到匹配项,则指定超时间隔。

Replace(String, String, MatchEvaluator, RegexOptions)

在指定的输入字符串中,将匹配指定正则表达式的所有字符串替换为由 MatchEvaluator 委托返回的字符串。 指定的选项修改匹配操作。

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

在指定的输入字符串中,将匹配指定正则表达式的所有字符串替换为指定的替换字符串。 其他参数指定修改匹配操作的选项,如果未找到匹配项,则指定超时间隔。

Replace(String, String, String, RegexOptions)

在指定的输入字符串中,将匹配指定正则表达式的所有字符串替换为指定的替换字符串。 指定的选项修改匹配操作。

Replace(String, MatchEvaluator)

在指定的输入字符串中,将匹配指定正则表达式的所有字符串替换为由 MatchEvaluator 委托返回的字符串。

Replace(String, MatchEvaluator, Int32)

在指定的输入字符串中,用由 MatchEvaluator 委托返回的字符串替换与正则表达式模式匹配的指定最大字符串数。

Replace(String, String, MatchEvaluator)

在指定的输入字符串中,将匹配指定正则表达式的所有字符串替换为由 MatchEvaluator 委托返回的字符串。

Replace(String, String, Int32)

在指定的输入字符串中,用指定的替换字符串替换与正则表达式模式匹配的指定最大字符串数。

Replace(String, String)

在指定的输入字符串中,将匹配正则表达式模式的所有字符串替换为指定的替换字符串。

Replace(String, String, Int32, Int32)

在指定的输入子字符串中,用指定的替换字符串替换与正则表达式模式匹配的指定最大字符串数。

Replace(String, MatchEvaluator, Int32, Int32)

Source:
Regex.Replace.cs
Source:
Regex.Replace.cs
Source:
Regex.Replace.cs

在指定的输入子字符串中,用由 MatchEvaluator 委托返回的字符串替换与正则表达式模式匹配的指定最大字符串数。

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

参数

input
String

要搜索匹配项的字符串。

evaluator
MatchEvaluator

检查每个匹配项并返回原始匹配字符串或替换字符串的自定义方法。

count
Int32

将发生替换的最大次数。

startat
Int32

搜索开始的输入字符串中的字符位置。

返回

与输入字符串完全相同的新字符串,但替换字符串取代每个匹配字符串的位置。 如果在当前实例中不匹配正则表达式模式,该方法将返回当前实例不变。

例外

inputevaluatornull

startat 小于零或大于 input的长度。

发生超时。 有关超时的详细信息,请参阅“备注”部分。

注解

如果满足以下任一条件,则 Regex.Replace(String, MatchEvaluator, Int32, Int32) 方法可用于替换正则表达式匹配项:

  • 替换字符串不能由正则表达式替换模式指定。
  • 替换字符串来自对匹配字符串执行的一些处理。
  • 替换字符串结果来自条件处理。

该方法等效于调用 Regex.Matches(String, Int32) 方法并将返回 MatchCollection 集合中的第一个 countMatch 对象传递给 evaluator 委托。

有关 startat的更多详细信息,请参阅 Match(String, Int32)的“备注”部分。

正则表达式是由当前 Regex 对象的构造函数定义的模式。

evaluator 参数是定义并检查每个匹配项的自定义方法的委托。 自定义方法必须具有以下签名才能匹配 MatchEvaluator 委托。

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

自定义方法返回替换匹配输入的字符串。

如果替换操作的执行时间超过 Regex.Regex(String, RegexOptions, TimeSpan) 构造函数指定的超时间隔,则会引发 RegexMatchTimeoutException 异常。 如果在调用构造函数时未设置超时间隔,则如果操作超出了为在其中创建 Regex 对象的应用程序域建立的任何超时值,则会引发异常。 如果在 Regex 构造函数调用或应用程序域的属性中未定义超时,或者超时值 Regex.InfiniteMatchTimeout,则不会引发异常

由于该方法在没有任何匹配项的情况下返回 input 不变,因此可以使用 Object.ReferenceEquals 方法来确定该方法是否已对输入字符串进行任何替换。

另请参阅

适用于

Replace(String, String, String)

Source:
Regex.Replace.cs
Source:
Regex.Replace.cs
Source:
Regex.Replace.cs

在指定的输入字符串中,将匹配指定正则表达式的所有字符串替换为指定的替换字符串。

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

参数

input
String

要搜索匹配项的字符串。

pattern
String

要匹配的正则表达式模式。

replacement
String

替换字符串。

返回

与输入字符串相同的新字符串,但替换字符串取代了每个匹配字符串的位置。 如果当前实例中 pattern 不匹配,该方法将返回当前实例不变。

例外

发生正则表达式分析错误。

inputpatternreplacementnull

发生超时。 有关超时的详细信息,请参阅“备注”部分。

示例

以下示例定义与一个或多个空格字符匹配的正则表达式 \s+。 替换字符串“,将其替换为单个空格字符。

using System;
using System.Text.RegularExpressions;

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

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

以下示例使用 Replace(String, String, String) 方法将 UNC 路径中的本地计算机和驱动器名称替换为本地文件路径。 正则表达式使用 Environment.MachineName 属性来包括本地计算机的名称,使用 Environment.GetLogicalDrives 方法包括逻辑驱动器的名称。 若要成功运行该示例,应将文本字符串“MyMachine”替换为本地计算机名称。

using System;
using System.Text.RegularExpressions;

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

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

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

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

正则表达式模式由以下表达式定义:

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

下表显示了如何解释正则表达式模式。

模式 描述
\\\\ 匹配两个连续反斜杠(\)字符。 由于反斜杠字符被解释为转义字符,因此必须使用另一个反斜杠对每个反斜杠进行转义。
(?i:" + Environment.MachineName + ") Environment.MachineName 属性返回的字符串执行不区分大小写的匹配。
(?:\.\w+)* 匹配句点(.)字符后跟一个或多个单词字符。 此匹配可以发生零次或多次。 未捕获匹配的子表达式。
\\ 匹配反斜杠(\)字符。
((?i:[" + driveNames + "])) 对由单个驱动器号组成的字符类执行不区分大小写的匹配。 此匹配是第一个捕获的子表达式。
\$ 匹配文本美元符号($)字符。

替换模式 $1 将整个匹配项替换为第一个捕获的子表达式。 也就是说,它将 UNC 计算机和驱动器名称替换为驱动器号。

注解

静态 Replace 方法等效于使用指定的正则表达式模式构造 Regex 对象,并调用实例方法 Replace

pattern 参数由正则表达式语言元素组成,这些元素以符号方式描述要匹配的字符串。 有关正则表达式的详细信息,请参阅 .NET 正则表达式正则表达式语言 - 快速参考。 搜索匹配项从 input 字符串的开头开始。

replacement 参数指定要替换 input中的每个匹配项的字符串。 replacement 可以包含文本文本和 替换的任意组合。 例如,替换模式 a*${test}b 插入字符串“a*”,后跟 test 捕获组匹配的子字符串(如果有)。后跟字符串“b”。 * 字符在替换模式中无法识别为元字符。

注意

替换是替换模式中唯一识别的正则表达式语言元素。 所有其他正则表达式语言元素(包括 字符转义)仅允许在正则表达式模式中使用,并且无法在替换模式中识别。

如果替换操作的执行时间超过为调用该方法的应用程序域指定的超时间隔,则会引发 RegexMatchTimeoutException 异常。 如果在应用程序域的属性中未定义超时,或者超时值 Regex.InfiniteMatchTimeout,则不会引发异常。

由于该方法在没有任何匹配项的情况下返回 input 不变,因此可以使用 Object.ReferenceEquals 方法来确定该方法是否已对输入字符串进行任何替换。

调用方说明

此方法在一个时间间隔后超时,该值等于调用它的应用程序域的默认超时值。 如果未为应用程序域定义超时值,则使用阻止方法超时的值 InfiniteMatchTimeout。 用于替换模式匹配的推荐静态方法是 Replace(String, String, String, RegexOptions, TimeSpan),这使你可以设置超时间隔。

另请参阅

适用于

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

Source:
Regex.Replace.cs
Source:
Regex.Replace.cs
Source:
Regex.Replace.cs

在指定的输入字符串中,将匹配指定正则表达式的所有子字符串替换为由 MatchEvaluator 委托返回的字符串。 其他参数指定修改匹配操作的选项,如果未找到匹配项,则指定超时间隔。

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

参数

input
String

要搜索匹配项的字符串。

pattern
String

要匹配的正则表达式模式。

evaluator
MatchEvaluator

检查每个匹配项并返回原始匹配字符串或替换字符串的自定义方法。

options
RegexOptions

提供匹配选项的枚举值的按位组合。

matchTimeout
TimeSpan

超时间隔,或 InfiniteMatchTimeout 指示方法不应超时。

返回

与输入字符串相同的新字符串,但替换字符串取代了每个匹配字符串的位置。 如果当前实例中 pattern 不匹配,该方法将返回当前实例不变。

例外

发生正则表达式分析错误。

inputpatternevaluatornull

options 不是 RegexOptions 值的有效按位组合。

-或-

matchTimeout 为负数、零或大于约 24 天。

发生超时。 有关超时的详细信息,请参阅“备注”部分。

示例

以下示例使用正则表达式从字符串中提取各个单词,然后使用 MatchEvaluator 委托调用一个名为 WordScramble 的方法,该方法会争用单词中的单个字母。 为此,WordScramble 方法将创建一个数组,其中包含匹配中的字符。 它还会创建一个并行数组,该数组使用随机浮点数进行填充。 数组通过调用 Array.Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>) 方法进行排序,排序数组作为 String 类构造函数的参数提供。 然后,WordScramble 方法返回此新创建的字符串。 正则表达式模式 \w+ 匹配一个或多个单词字符;正则表达式引擎将继续将字符添加到匹配项,直到遇到非单词字符(例如空格字符)。 对 Replace(String, String, MatchEvaluator, RegexOptions) 方法的调用包括 RegexOptions.IgnorePatternWhitespace 选项,以便正则表达式模式中的注释 \w+ # Matches all the characters in a word. 被正则表达式引擎忽略。

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

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

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

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

注解

如果满足以下任一条件,则 Regex.Replace(String, String, MatchEvaluator, RegexOptions) 方法可用于替换正则表达式匹配项:

  • 如果替换字符串无法由正则表达式替换模式轻松指定。

  • 如果替换字符串导致对匹配字符串执行的一些处理。

  • 如果替换字符串来自条件处理的结果。

该方法等效于调用 Regex.Matches(String, String, RegexOptions) 方法并将返回 MatchCollection 集合中的每个 Match 对象传递给 evaluator 委托。

pattern 参数由正则表达式语言元素组成,这些元素以符号方式描述要匹配的字符串。 有关正则表达式的详细信息,请参阅 .NET 正则表达式正则表达式语言 - 快速参考

evaluator 参数是定义并检查每个匹配项的自定义方法的委托。 自定义方法必须具有以下签名才能匹配 MatchEvaluator 委托。

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

自定义方法返回替换匹配输入的字符串。

如果为 options 参数指定 RightToLeft,则搜索匹配项从输入字符串的末尾开始,然后向左移动;否则,搜索从输入字符串的开头开始,然后向右移动。

matchTimeout 参数指定模式匹配方法在超时之前应尝试查找匹配的时间。设置超时间隔可防止依赖过度回溯的正则表达式出现“在处理包含接近匹配项的输入时停止响应”。 有关详细信息,请参阅 正则表达式的最佳做法回溯。 如果未在该时间间隔中找到匹配项,该方法将引发 RegexMatchTimeoutException 异常。 matchTimeout 替代为方法在其中执行的应用程序域定义的任何默认超时值。

由于该方法在没有任何匹配项的情况下返回 input 不变,因此可以使用 Object.ReferenceEquals 方法来确定该方法是否已对输入字符串进行任何替换。

调用方说明

建议将 matchTimeout 参数设置为适当的值,例如两秒。 如果通过指定 InfiniteMatchTimeout来禁用超时,则正则表达式引擎提供略微更好的性能。 但是,应仅在以下情况下禁用超时:

  • 当正则表达式处理的输入派生自已知且受信任的源或包含静态文本时。 这不包括用户动态输入的文本。

  • 当正则表达式模式经过全面测试以确保它有效地处理匹配项、非匹配项和接近匹配项时。

  • 当正则表达式模式不包含任何已知在处理接近匹配时导致过度回溯的语言元素。

另请参阅

适用于

Replace(String, String, MatchEvaluator, RegexOptions)

Source:
Regex.Replace.cs
Source:
Regex.Replace.cs
Source:
Regex.Replace.cs

在指定的输入字符串中,将匹配指定正则表达式的所有字符串替换为由 MatchEvaluator 委托返回的字符串。 指定的选项修改匹配操作。

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

参数

input
String

要搜索匹配项的字符串。

pattern
String

要匹配的正则表达式模式。

evaluator
MatchEvaluator

检查每个匹配项并返回原始匹配字符串或替换字符串的自定义方法。

options
RegexOptions

提供匹配选项的枚举值的按位组合。

返回

与输入字符串完全相同的新字符串,但替换字符串取代每个匹配字符串的位置。 如果当前实例中 pattern 不匹配,该方法将返回当前实例不变。

例外

发生正则表达式分析错误。

inputpatternevaluatornull

options 不是 RegexOptions 值的有效按位组合。

发生超时。 有关超时的详细信息,请参阅“备注”部分。

示例

以下示例使用正则表达式从字符串中提取各个单词,然后使用 MatchEvaluator 委托调用一个名为 WordScramble 的方法,该方法会争用单词中的单个字母。 为此,WordScramble 方法将创建一个数组,其中包含匹配中的字符。 它还会创建一个并行数组,该数组使用随机浮点数进行填充。 数组通过调用 Array.Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>) 方法进行排序,排序数组作为 String 类构造函数的参数提供。 然后,WordScramble 方法返回此新创建的字符串。 正则表达式模式 \w+ 匹配一个或多个单词字符;正则表达式引擎将继续将字符添加到匹配项,直到遇到非单词字符(例如空格字符)。 对 Replace(String, String, MatchEvaluator, RegexOptions) 方法的调用包括 RegexOptions.IgnorePatternWhitespace 选项,以便正则表达式模式中的注释 \w+ # Matches all the characters in a word. 被正则表达式引擎忽略。

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

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

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

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

注解

如果满足以下任一条件,则 Regex.Replace(String, String, MatchEvaluator, RegexOptions) 方法可用于替换正则表达式匹配项:

  • 替换字符串不能由正则表达式替换模式指定。

  • 替换字符串来自对匹配字符串执行的一些处理。

  • 替换字符串结果来自条件处理。

该方法等效于调用 Regex.Matches(String, String, RegexOptions) 方法并将返回 MatchCollection 集合中的每个 Match 对象传递给 evaluator 委托。

pattern 参数由正则表达式语言元素组成,这些元素以符号方式描述要匹配的字符串。 有关正则表达式的详细信息,请参阅 .NET 正则表达式正则表达式语言 - 快速参考

evaluator 参数是定义并检查每个匹配项的自定义方法的委托。 自定义方法必须具有以下签名才能匹配 MatchEvaluator 委托。

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

自定义方法返回替换匹配输入的字符串。

如果为 options 参数指定 RightToLeft,则搜索匹配项从输入字符串的末尾开始,然后向左移动;否则,搜索从输入字符串的开头开始,然后向右移动。

如果替换操作的执行时间超过为调用该方法的应用程序域指定的超时间隔,则会引发 RegexMatchTimeoutException 异常。 如果在应用程序域的属性中未定义超时,或者超时值 Regex.InfiniteMatchTimeout,则不会引发异常。

由于该方法在没有任何匹配项的情况下返回 input 不变,因此可以使用 Object.ReferenceEquals 方法来确定该方法是否已对输入字符串进行任何替换。

另请参阅

适用于

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

Source:
Regex.Replace.cs
Source:
Regex.Replace.cs
Source:
Regex.Replace.cs

在指定的输入字符串中,将匹配指定正则表达式的所有字符串替换为指定的替换字符串。 其他参数指定修改匹配操作的选项,如果未找到匹配项,则指定超时间隔。

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

参数

input
String

要搜索匹配项的字符串。

pattern
String

要匹配的正则表达式模式。

replacement
String

替换字符串。

options
RegexOptions

提供匹配选项的枚举值的按位组合。

matchTimeout
TimeSpan

超时间隔,或 InfiniteMatchTimeout 指示方法不应超时。

返回

与输入字符串相同的新字符串,但替换字符串取代了每个匹配字符串的位置。 如果当前实例中 pattern 不匹配,该方法将返回当前实例不变。

例外

发生正则表达式分析错误。

inputpatternreplacementnull

options 不是 RegexOptions 值的有效按位组合。

-或-

matchTimeout 为负数、零或大于约 24 天。

发生超时。 有关超时的详细信息,请参阅“备注”部分。

示例

以下示例使用 Replace(String, String, String, RegexOptions, TimeSpan) 方法将 UNC 路径中的本地计算机和驱动器名称替换为本地文件路径。 正则表达式使用 Environment.MachineName 属性来包括本地计算机的名称和 Environment.GetLogicalDrives 方法以包括逻辑驱动器的名称。 所有正则表达式字符串比较都是不区分大小写的,如果在 0.5 秒内找不到匹配项,则任何单个替换操作都会超时。 若要成功运行该示例,应将文本字符串“MyMachine”替换为本地计算机名称。

using System;
using System.Text.RegularExpressions;

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

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

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

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

正则表达式模式由以下表达式定义:

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

下表显示了如何解释正则表达式模式。

模式 描述
\\\\ 匹配两个连续反斜杠(\)字符。 由于反斜杠字符被解释为转义字符,因此必须使用另一个反斜杠对每个反斜杠进行转义。
+ Environment.MachineName + 匹配由 Environment.MachineName 属性返回的字符串。
(?:\.\w+)* 匹配句点(.)字符后跟一个或多个单词字符。 此匹配可以发生零次或多次。 未捕获匹配的子表达式。
\\ 匹配反斜杠(\)字符。
([" + driveNames + "]) 匹配由单个驱动器号组成的字符类。 此匹配是第一个捕获的子表达式。
\$ 匹配文本美元符号($)字符。

替换模式 $1 将整个匹配项替换为第一个捕获的子表达式。 也就是说,它将 UNC 计算机和驱动器名称替换为驱动器号。

注解

静态 Replace 方法等效于使用指定的正则表达式模式构造 Regex 对象,并调用实例方法 Replace

pattern 参数由正则表达式语言元素组成,这些元素以符号方式描述要匹配的字符串。 有关正则表达式的详细信息,请参阅 .NET 正则表达式正则表达式语言 - 快速参考。 如果为 options 参数指定 RightToLeft,则搜索匹配项从输入字符串的末尾开始,然后向左移动;否则,搜索从输入字符串的开头开始,然后向右移动。

replacement 参数指定要替换 input中的每个匹配项的字符串。 replacement 可以包含文本文本和 替换的任意组合。 例如,替换模式 a*${test}b 插入字符串“a*”,后跟 test 捕获组匹配的子字符串(如果有)。后跟字符串“b”。 * 字符在替换模式中无法识别为元字符。

注意

替换是替换模式中唯一识别的正则表达式语言元素。 所有其他正则表达式语言元素(包括 字符转义)仅允许在正则表达式模式中使用,并且无法在替换模式中识别。

matchTimeout 参数指定模式匹配方法在超时之前应尝试查找匹配的时间。设置超时间隔可防止依赖过度回溯的正则表达式在处理包含接近匹配项的输入时停止响应。 有关详细信息,请参阅 正则表达式的最佳做法回溯。 如果未在该时间间隔中找到匹配项,该方法将引发 RegexMatchTimeoutException 异常。 matchTimeout 替代为方法在其中执行的应用程序域定义的任何默认超时值。

由于该方法在没有任何匹配项的情况下返回 input 不变,因此可以使用 Object.ReferenceEquals 方法来确定该方法是否已对输入字符串进行任何替换。

调用方说明

建议将 matchTimeout 参数设置为适当的值,例如两秒。 如果通过指定 InfiniteMatchTimeout来禁用超时,则正则表达式引擎提供略微更好的性能。 但是,应仅在以下情况下禁用超时:

  • 当正则表达式处理的输入派生自已知且受信任的源或包含静态文本时。 这不包括用户动态输入的文本。

  • 当正则表达式模式经过全面测试以确保它有效地处理匹配项、非匹配项和接近匹配项时。

  • 当正则表达式模式不包含任何已知在处理接近匹配时导致过度回溯的语言元素。

另请参阅

适用于

Replace(String, String, String, RegexOptions)

Source:
Regex.Replace.cs
Source:
Regex.Replace.cs
Source:
Regex.Replace.cs

在指定的输入字符串中,将匹配指定正则表达式的所有字符串替换为指定的替换字符串。 指定的选项修改匹配操作。

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

参数

input
String

要搜索匹配项的字符串。

pattern
String

要匹配的正则表达式模式。

replacement
String

替换字符串。

options
RegexOptions

提供匹配选项的枚举值的按位组合。

返回

与输入字符串相同的新字符串,但替换字符串取代了每个匹配字符串的位置。 如果当前实例中 pattern 不匹配,该方法将返回当前实例不变。

例外

发生正则表达式分析错误。

inputpatternreplacementnull

options 不是 RegexOptions 值的有效按位组合。

发生超时。 有关超时的详细信息,请参阅“备注”部分。

示例

以下示例使用 Replace(String, String, String, RegexOptions) 方法将 UNC 路径中的本地计算机和驱动器名称替换为本地文件路径。 正则表达式使用 Environment.MachineName 属性来包括本地计算机的名称,使用 Environment.GetLogicalDrives 方法包括逻辑驱动器的名称。 所有正则表达式字符串比较都区分大小写。 若要成功运行该示例,应将文本字符串“MyMachine”替换为本地计算机名称。

using System;
using System.Text.RegularExpressions;

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

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

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

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

正则表达式模式由以下表达式定义:

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

下表显示了如何解释正则表达式模式。

模式 描述
\\\\ 匹配两个连续反斜杠(\)字符。 由于反斜杠字符被解释为转义字符,因此必须使用另一个反斜杠对每个反斜杠进行转义。
+ Environment.MachineName + 匹配由 Environment.MachineName 属性返回的字符串。
(?:\.\w+)* 匹配句点(.)字符后跟一个或多个单词字符。 此匹配可以发生零次或多次。 未捕获匹配的子表达式。
\\ 匹配反斜杠(\)字符。
([" + driveNames + "]) 匹配由单个驱动器号组成的字符类。 此匹配是第一个捕获的子表达式。
\$ 匹配文本美元符号($)字符。

替换模式 $1 将整个匹配项替换为第一个捕获的子表达式。 也就是说,它将 UNC 计算机和驱动器名称替换为驱动器号。

注解

静态 Replace 方法等效于使用指定的正则表达式模式构造 Regex 对象,并调用实例方法 Replace

pattern 参数由正则表达式语言元素组成,这些元素以符号方式描述要匹配的字符串。 有关正则表达式的详细信息,请参阅 .NET 正则表达式正则表达式语言 - 快速参考。 如果为 options 参数指定 RightToLeft,则搜索匹配项从输入字符串的末尾开始,然后向左移动;否则,搜索从输入字符串的开头开始,然后向右移动。

replacement 参数指定要替换 input中的每个匹配项的字符串。 replacement 可以包含文本文本和 替换的任意组合。 例如,替换模式 a*${test}b 插入字符串“a*”,后跟 test 捕获组匹配的子字符串(如果有)。后跟字符串“b”。 * 字符在替换模式中无法识别为元字符。

注意

替换是替换模式中唯一识别的正则表达式语言元素。 所有其他正则表达式语言元素(包括 字符转义)仅允许在正则表达式模式中使用,并且无法在替换模式中识别。

如果替换操作的执行时间超过为调用该方法的应用程序域指定的超时间隔,则会引发 RegexMatchTimeoutException 异常。 如果在应用程序域的属性中未定义超时,或者超时值 Regex.InfiniteMatchTimeout,则不会引发异常。

由于该方法在没有任何匹配项的情况下返回 input 不变,因此可以使用 Object.ReferenceEquals 方法来确定该方法是否已对输入字符串进行任何替换。

调用方说明

此方法在一个时间间隔后超时,该值等于调用它的应用程序域的默认超时值。 如果未为应用程序域定义超时值,则使用阻止方法超时的值 InfiniteMatchTimeout。 用于替换模式匹配的推荐静态方法是 Replace(String, String, String, RegexOptions, TimeSpan),这使你可以设置超时间隔。

另请参阅

适用于

Replace(String, MatchEvaluator)

Source:
Regex.Replace.cs
Source:
Regex.Replace.cs
Source:
Regex.Replace.cs

在指定的输入字符串中,将匹配指定正则表达式的所有字符串替换为由 MatchEvaluator 委托返回的字符串。

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

参数

input
String

要搜索匹配项的字符串。

evaluator
MatchEvaluator

检查每个匹配项并返回原始匹配字符串或替换字符串的自定义方法。

返回

与输入字符串完全相同的新字符串,但替换字符串取代每个匹配字符串的位置。 如果在当前实例中不匹配正则表达式模式,该方法将返回当前实例不变。

例外

inputevaluatornull

发生超时。 有关超时的详细信息,请参阅“备注”部分。

示例

下面的代码示例显示原始字符串,匹配原始字符串中的每个单词,将每个匹配项的第一个字符转换为大写,然后显示转换后的字符串。

using System;
using System.Text.RegularExpressions;

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

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

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

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

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

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

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

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

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

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

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

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

注解

如果满足以下任一条件,则 Regex.Replace(String, MatchEvaluator) 方法可用于替换正则表达式匹配项:

  • 替换字符串不能由正则表达式替换模式指定。

  • 替换字符串来自对匹配字符串执行的一些处理。

  • 替换字符串结果来自条件处理。

该方法等效于调用 Regex.Matches(String) 方法并将返回 MatchCollection 集合中的每个 Match 对象传递给 evaluator 委托。

正则表达式是由当前 Regex 对象的构造函数定义的模式。

evaluator 参数是定义并检查每个匹配项的自定义方法的委托。 自定义方法必须具有以下签名才能匹配 MatchEvaluator 委托。

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

自定义方法返回替换匹配输入的字符串。

如果替换操作的执行时间超过 Regex.Regex(String, RegexOptions, TimeSpan) 构造函数指定的超时间隔,则会引发 RegexMatchTimeoutException 异常。 如果在调用构造函数时未设置超时间隔,则如果操作超出了为在其中创建 Regex 对象的应用程序域建立的任何超时值,则会引发异常。 如果在 Regex 构造函数调用或应用程序域的属性中未定义超时,或者超时值 Regex.InfiniteMatchTimeout,则不会引发异常

由于该方法在没有任何匹配项的情况下返回 input 不变,因此可以使用 Object.ReferenceEquals 方法来确定该方法是否已对输入字符串进行任何替换。

另请参阅

适用于

Replace(String, MatchEvaluator, Int32)

Source:
Regex.Replace.cs
Source:
Regex.Replace.cs
Source:
Regex.Replace.cs

在指定的输入字符串中,用由 MatchEvaluator 委托返回的字符串替换与正则表达式模式匹配的指定最大字符串数。

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

参数

input
String

要搜索匹配项的字符串。

evaluator
MatchEvaluator

检查每个匹配项并返回原始匹配字符串或替换字符串的自定义方法。

count
Int32

将发生替换的最大次数。

返回

与输入字符串完全相同的新字符串,但替换字符串取代每个匹配字符串的位置。 如果在当前实例中不匹配正则表达式模式,该方法将返回当前实例不变。

例外

inputevaluatornull

发生超时。 有关超时的详细信息,请参阅“备注”部分。

示例

以下示例使用正则表达式故意将列表中的一半单词拼写错误。 它使用正则表达式 \w*(ie|ei)\w* 匹配包含字符“ie”或“ei”的单词。 它将匹配单词的前半部分传递给 ReverseLetter 方法,该方法反过来又使用 Replace(String, String, String, RegexOptions) 方法来反转匹配字符串中的“i”和“e”。 其余单词保持不变。

using System;
using System.Text.RegularExpressions;

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

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

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

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

正则表达式 \w*(ie|ei)\w* 的定义如下表所示。

模式 描述
\w* 匹配零个或多个单词字符。
(ie|ei) 匹配“ie”或“ei”。
\w* 匹配零个或多个单词字符。

ReverseLetter 方法中的正则表达式模式 ([ie])([ie]) 匹配 diphthong“ie”或“ei”中的第一个“i”或“e”,并将字母分配给第一个捕获组。 它与第二个“i”或“e”匹配,并将字母分配给第二个捕获组。 然后,使用替换模式 $2$1调用 Replace(String, String, String) 方法来反转这两个字符。

注解

如果满足以下任一条件,则 Regex.Replace(String, MatchEvaluator, Int32) 方法可用于替换正则表达式匹配项:

  • 替换字符串不能由正则表达式替换模式指定。

  • 替换字符串来自对匹配字符串执行的一些处理。

  • 替换字符串结果来自条件处理。

该方法等效于调用 Regex.Matches(String) 方法并将返回 MatchCollection 集合中的第一个 countMatch 对象传递给 evaluator 委托。

正则表达式是由当前 Regex 对象的构造函数定义的模式。

evaluator 参数是定义并检查每个匹配项的自定义方法的委托。 自定义方法必须具有以下签名才能匹配 MatchEvaluator 委托。

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

自定义方法返回替换匹配输入的字符串。

如果替换操作的执行时间超过 Regex.Regex(String, RegexOptions, TimeSpan) 构造函数指定的超时间隔,则会引发 RegexMatchTimeoutException 异常。 如果在调用构造函数时未设置超时间隔,则如果操作超出了为在其中创建 Regex 对象的应用程序域建立的任何超时值,则会引发异常。 如果在 Regex 构造函数调用或应用程序域的属性中未定义超时,或者超时值 Regex.InfiniteMatchTimeout,则不会引发异常

由于该方法在没有任何匹配项的情况下返回 input 不变,因此可以使用 Object.ReferenceEquals 方法来确定该方法是否已对输入字符串进行任何替换。

另请参阅

适用于

Replace(String, String, MatchEvaluator)

Source:
Regex.Replace.cs
Source:
Regex.Replace.cs
Source:
Regex.Replace.cs

在指定的输入字符串中,将匹配指定正则表达式的所有字符串替换为由 MatchEvaluator 委托返回的字符串。

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

参数

input
String

要搜索匹配项的字符串。

pattern
String

要匹配的正则表达式模式。

evaluator
MatchEvaluator

检查每个匹配项并返回原始匹配字符串或替换字符串的自定义方法。

返回

与输入字符串完全相同的新字符串,但替换字符串取代每个匹配字符串的位置。 如果当前实例中 pattern 不匹配,该方法将返回当前实例不变。

例外

发生正则表达式分析错误。

inputpatternevaluatornull

发生超时。 有关超时的详细信息,请参阅“备注”部分。

示例

以下示例使用正则表达式从字符串中提取各个单词,然后使用 MatchEvaluator 委托调用一个名为 WordScramble 的方法,该方法会争用单词中的单个字母。 为此,WordScramble 方法将创建一个数组,其中包含匹配中的字符。 它还会创建一个并行数组,该数组使用随机浮点数进行填充。 数组通过调用 Array.Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>) 方法进行排序,排序数组作为 String 类构造函数的参数提供。 然后,WordScramble 方法返回此新创建的字符串。 正则表达式模式 \w+ 匹配一个或多个单词字符;正则表达式引擎将继续将字符添加到匹配项,直到遇到非单词字符(例如空格字符)。

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

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

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

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

注解

如果满足以下任一条件,则 Regex.Replace(String, String, MatchEvaluator) 方法可用于替换正则表达式匹配项:

  • 替换字符串不能由正则表达式替换模式指定。

  • 替换字符串来自对匹配字符串执行的一些处理。

  • 替换字符串结果来自条件处理。

该方法等效于调用 Regex.Matches(String, String) 方法并将返回 MatchCollection 集合中的每个 Match 对象传递给 evaluator 委托。

pattern 参数由正则表达式语言元素组成,这些元素以符号方式描述要匹配的字符串。 有关正则表达式的详细信息,请参阅 .NET 正则表达式正则表达式语言 - 快速参考

evaluator 参数是定义并检查每个匹配项的自定义方法的委托。 自定义方法必须具有以下签名才能匹配 MatchEvaluator 委托。

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

自定义方法返回替换匹配输入的字符串。

如果替换操作的执行时间超过为调用该方法的应用程序域指定的超时间隔,则会引发 RegexMatchTimeoutException 异常。 如果在应用程序域的属性中未定义超时,或者超时值 Regex.InfiniteMatchTimeout,则不会引发异常。

由于该方法在没有任何匹配项的情况下返回 input 不变,因此可以使用 Object.ReferenceEquals 方法来确定该方法是否已对输入字符串进行任何替换。

调用方说明

此方法在一个时间间隔后超时,该值等于调用它的应用程序域的默认超时值。 如果未为应用程序域定义超时值,则使用阻止方法超时的值 InfiniteMatchTimeout。 用于评估和替换模式匹配的推荐静态方法 Replace(String, String, MatchEvaluator, RegexOptions, TimeSpan),这使你可以设置超时间隔。

另请参阅

适用于

Replace(String, String, Int32)

Source:
Regex.Replace.cs
Source:
Regex.Replace.cs
Source:
Regex.Replace.cs

在指定的输入字符串中,用指定的替换字符串替换与正则表达式模式匹配的指定最大字符串数。

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

参数

input
String

要搜索匹配项的字符串。

replacement
String

替换字符串。

count
Int32

可以替换的最大次数。

返回

与输入字符串相同的新字符串,但替换字符串取代了每个匹配字符串的位置。 如果在当前实例中不匹配正则表达式模式,该方法将返回当前实例不变。

例外

inputreplacementnull

发生超时。 有关超时的详细信息,请参阅“备注”部分。

示例

以下示例将重复字符的前五个匹配项替换为一个字符。 正则表达式模式 (\w)\1 匹配单个字符的连续匹配项,并将第一个匹配项分配给第一个捕获组。 替换模式 $1 将整个匹配项替换为第一个捕获的组。

using System;
using System.Text.RegularExpressions;

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

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

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

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

注解

搜索匹配项从 input 字符串的开头开始。 正则表达式是由当前 Regex 对象的构造函数定义的模式。 如果 count 为负数,则替换操作会继续到字符串的末尾。 如果 count 超过匹配项数,则替换所有匹配项。

replacement 参数指定替换 input中的第一个 count 匹配项的字符串。 replacement 可以包含文本文本和 替换的任意组合。 例如,替换模式 a*${test}b 插入字符串“a*”,后跟 test 捕获组匹配的子字符串(如果有)。后跟字符串“b”。 * 字符在替换模式中无法识别为元字符。

注意

替换是替换模式中唯一识别的正则表达式语言元素。 所有其他正则表达式语言元素(包括 字符转义)仅允许在正则表达式模式中使用,并且无法在替换模式中识别。

如果替换操作的执行时间超过 Regex.Regex(String, RegexOptions, TimeSpan) 构造函数指定的超时间隔,则会引发 RegexMatchTimeoutException 异常。 如果在调用构造函数时未设置超时间隔,则如果操作超出了为在其中创建 Regex 对象的应用程序域建立的任何超时值,则会引发异常。 如果在 Regex 构造函数调用或应用程序域的属性中未定义超时,或者超时值 Regex.InfiniteMatchTimeout,则不会引发异常

由于该方法在没有任何匹配项的情况下返回 input 不变,因此可以使用 Object.ReferenceEquals 方法来确定该方法是否已对输入字符串进行任何替换。

另请参阅

适用于

Replace(String, String)

Source:
Regex.Replace.cs
Source:
Regex.Replace.cs
Source:
Regex.Replace.cs

在指定的输入字符串中,将匹配正则表达式模式的所有字符串替换为指定的替换字符串。

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

参数

input
String

要搜索匹配项的字符串。

replacement
String

替换字符串。

返回

与输入字符串相同的新字符串,但替换字符串取代了每个匹配字符串的位置。 如果在当前实例中不匹配正则表达式模式,该方法将返回当前实例不变。

例外

inputreplacementnull

发生超时。 有关超时的详细信息,请参阅“备注”部分。

示例

以下示例定义与一个或多个空格字符匹配的正则表达式 \s+。 替换字符串“,将其替换为单个空格字符。

using System;
using System.Text.RegularExpressions;

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

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

以下示例定义正则表达式、(\p{Sc}\s?)?(\d+\.?((?<=\.)\d+)?)(?(1)|\s?\p{Sc})?和替换模式($2),该模式从数值中删除前导或尾随货币符号。

using System;
using System.Text.RegularExpressions;

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

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

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

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

正则表达式的解释如下表所示。

模式 描述
\p{Sc} 匹配货币符号。 {Sc} 表示属于 Unicode 符号、货币类别的任何字符。
\s? 匹配零个或一个空格字符。
(\p{Sc}\s?)? 匹配货币符号组合的零个或一个匹配项,后跟零个或一个空格字符。 这是第一个捕获组。
\d+ 匹配一个或多个十进制数字。
\.? 匹配句点的零个或一个匹配项(用作小数分隔符)。
((?<=\.)\d+)? 如果句点为前一个字符,则匹配一个或多个十进制数字。 此模式可以匹配零个或一次。
(\d+\.?((?<=\.)\d+)?) 匹配一个或多个十进制数字的模式,后跟可选句点和其他十进制数字。 这是第二个捕获组。 调用 Replace(String, String) 方法会将整个匹配项替换为此捕获组的值。
(?(1)|\s?\p{Sc})? 如果第一个捕获的组存在,则匹配空字符串。 否则,匹配零个或一个空格字符,后跟货币符号。

注解

搜索匹配项从 input 字符串的开头开始。 正则表达式是由当前 Regex 对象的构造函数定义的模式。

replacement 参数指定要替换 input中的每个匹配项的字符串。 replacement 可以包含文本文本和 替换的任意组合。 例如,替换模式 a*${test}b 插入字符串“a*”,后跟 test 捕获组匹配的子字符串(如果有)。后跟字符串“b”。 * 字符在替换模式中无法识别为元字符。

注意

替换是替换模式中唯一识别的正则表达式语言元素。 所有其他正则表达式语言元素(包括 字符转义)仅允许在正则表达式模式中使用,并且无法在替换模式中识别。

如果替换操作的执行时间超过 Regex.Regex(String, RegexOptions, TimeSpan) 构造函数指定的超时间隔,则会引发 RegexMatchTimeoutException 异常。 如果在调用构造函数时未设置超时间隔,则如果操作超出了为在其中创建 Regex 对象的应用程序域建立的任何超时值,则会引发异常。 如果在 Regex 构造函数调用或应用程序域的属性中未定义超时,或者超时值 Regex.InfiniteMatchTimeout,则不会引发异常

由于该方法在没有任何匹配项的情况下返回 input 不变,因此可以使用 Object.ReferenceEquals 方法来确定该方法是否已对输入字符串进行任何替换。

另请参阅

适用于

Replace(String, String, Int32, Int32)

Source:
Regex.Replace.cs
Source:
Regex.Replace.cs
Source:
Regex.Replace.cs

在指定的输入子字符串中,用指定的替换字符串替换与正则表达式模式匹配的指定最大字符串数。

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

参数

input
String

要搜索匹配项的字符串。

replacement
String

替换字符串。

count
Int32

可发生替换的最大次数。

startat
Int32

搜索开始的输入字符串中的字符位置。

返回

与输入字符串相同的新字符串,但替换字符串取代了每个匹配字符串的位置。 如果在当前实例中不匹配正则表达式模式,该方法将返回当前实例不变。

例外

inputreplacementnull

startat 小于零或大于 input的长度。

发生超时。 有关超时的详细信息,请参阅“备注”部分。

示例

以下示例将字符串的第一行全部空格。 它定义与文本行匹配的正则表达式模式 ^.*$,调用 Match(String) 方法以匹配字符串的第一行,并使用 Match.IndexMatch.Count 属性来确定第二行的起始位置。

using System;
using System.Text.RegularExpressions;

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

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

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

正则表达式模式 ^.*$ 的定义如下表所示。

模式 描述
^ 匹配行的开头。 (请注意,Regex 对象是使用 RegexOptions.Multiline 选项实例化的;否则,此字符类将仅匹配输入字符串的开头。
.* 匹配任何字符零次或多次。
$ 匹配行尾。 (请注意,Regex 对象是使用 RegexOptions.Multiline 选项实例化的;否则,此字符类将仅匹配输入字符串的开头。

替换字符串(vbCrLf + "$&" Visual Basic 中的 C# "\n$&")在匹配的字符串之前添加新行。 请注意,C# 示例中的 \n 被 C# 编译器解释为换行符;它不表示正则表达式字符转义。

注解

搜索匹配项从 startat 参数指定的位置处的 input 字符串开始。 正则表达式是由当前 Regex 对象的构造函数定义的模式。 如果 count 为负数,则替换操作会继续到字符串的末尾。 如果 count 超过匹配项数,则替换所有匹配项。

有关 startat的更多详细信息,请参阅 Match(String, Int32)的“备注”部分。

replacement 参数指定要替换 input中的每个匹配项的字符串。 replacement 可以包含文本文本和 替换的任意组合。 例如,替换模式 a*${test}b 插入字符串“a*”,后跟 test 捕获组匹配的子字符串(如果有)。后跟字符串“b”。 * 字符在替换模式中无法识别为元字符。

注意

替换是替换模式中唯一识别的正则表达式语言元素。 所有其他正则表达式语言元素(包括 字符转义)仅允许在正则表达式模式中使用,并且无法在替换模式中识别。

如果替换操作的执行时间超过 Regex.Regex(String, RegexOptions, TimeSpan) 构造函数指定的超时间隔,则会引发 RegexMatchTimeoutException 异常。 如果在调用构造函数时未设置超时间隔,则如果操作超出了为在其中创建 Regex 对象的应用程序域建立的任何超时值,则会引发异常。 如果在 Regex 构造函数调用或应用程序域的属性中未定义超时,或者超时值 Regex.InfiniteMatchTimeout,则不会引发异常

由于该方法在没有任何匹配项的情况下返回 input 不变,因此可以使用 Object.ReferenceEquals 方法来确定该方法是否已对输入字符串进行任何替换。

另请参阅

适用于