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)

在指定的输入子字符串内,使用 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)如果以下任一条件为 true, 方法可用于替换正则表达式匹配项:

  • 正则表达式替换模式无法轻松指定替换字符串。
  • 替换字符串是在匹配字符串上完成的一些处理后产生的。
  • 替换字符串来自条件处理。

方法等效于调用 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

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

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

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

另请参阅

适用于

Replace(String, String, 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

要搜索匹配项的字符串。

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)

在指定的输入字符串中,使用由 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)如果以下任一条件为 true, 方法可用于替换正则表达式匹配项:

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

  • 如果替换字符串来自对匹配字符串执行的某种处理。

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

方法等效于调用 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 适当的值,例如 2 秒。 如果通过指定 InfiniteMatchTimeout来禁用超时,则正则表达式引擎提供的性能稍好一些。 但是,应仅在以下情况下禁用超时:

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

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

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

另请参阅

适用于

Replace(String, String, MatchEvaluator, RegexOptions)

在指定的输入字符串中,使用由 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

注解

如果以下任一条件为 true,则 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)

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

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 适当的值,例如 2 秒。 如果通过指定 InfiniteMatchTimeout来禁用超时,则正则表达式引擎提供的性能稍好一些。 但是,应仅在以下情况下禁用超时:

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

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

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

另请参阅

适用于

Replace(String, String, String, RegexOptions)

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

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)

在指定的输入字符串中,使用由 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)如果以下任一条件为 true, 方法可用于替换正则表达式匹配项:

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

  • 替换字符串是在匹配字符串上完成的一些处理后产生的。

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

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

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

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

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

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

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

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

另请参阅

适用于

Replace(String, MatchEvaluator, Int32)

在指定的输入字符串内,使用 MatchEvaluator 委托返回的字符串替换与某个正则表达式模式匹配的字符串(其数目为指定的最大数目)。

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

参数

input
String

要搜索匹配项的字符串。

evaluator
MatchEvaluator

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

count
Int32

进行替换的最大次数。

返回

一个与输入字符串基本相同的新字符串,唯一的差别在于,其中的每个匹配字符串已被一个替换字符串代替。 如果正则表达式模式与当前实例不匹配,则此方法返回未更改的当前实例。

例外

inputevaluatornull

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

示例

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

using System;
using System.Text.RegularExpressions;

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

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

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

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

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

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

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

注解

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

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

  • 替换字符串是在匹配字符串上完成的一些处理后产生的。

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

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

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

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

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

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

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

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

另请参阅

适用于

Replace(String, String, MatchEvaluator)

在指定的输入字符串中,使用由 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)如果以下任一条件为 true, 方法可用于替换正则表达式匹配项:

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

  • 替换字符串是在匹配字符串上完成的一些处理后产生的。

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

方法等效于调用 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)

在指定输入字符串内,使用指定替换字符串替换与某个正则表达式模式匹配的字符串(其数目为指定的最大数目)。

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

注意

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

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

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

另请参阅

适用于

Replace(String, 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

要搜索匹配项的字符串。

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”。 * 字符在替换模式中无法识别为元字符。

注意

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

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

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

另请参阅

适用于

Replace(String, String, Int32, Int32)

在指定输入子字符串内,使用指定替换字符串替换与某个正则表达式模式匹配的字符串(其数目为指定的最大数目)。

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 选项实例化的;否则,此字符类将仅匹配输入 string 的开头。)
.* 零次或多次匹配任何字符。
$ 匹配线条的末尾。 (请注意, Regex 对象是使用 RegexOptions.Multiline 选项实例化的;否则,此字符类将仅匹配输入 string 的开头。)

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

注解

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

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

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

注意

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

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

由于如果没有匹配项,方法将返回 input 不变,因此可以使用 Object.ReferenceEquals 方法确定是否对输入字符串进行了任何替换。

另请参阅

适用于