ערוך

שתף באמצעות


Regex.Replace Method

Definition

In a specified input string, replaces strings that match a regular expression pattern with a specified replacement string.

Overloads

Replace(String, String, String, RegexOptions)

In a specified input string, replaces all strings that match a specified regular expression with a specified replacement string. Specified options modify the matching operation.

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

In a specified input string, replaces all strings that match a specified regular expression with a specified replacement string. Additional parameters specify options that modify the matching operation and a time-out interval if no match is found.

Replace(String, MatchEvaluator, Int32, Int32)

In a specified input substring, replaces a specified maximum number of strings that match a regular expression pattern with a string returned by a MatchEvaluator delegate.

Replace(String, String, MatchEvaluator, RegexOptions)

In a specified input string, replaces all strings that match a specified regular expression with a string returned by a MatchEvaluator delegate. Specified options modify the matching operation.

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

In a specified input string, replaces all substrings that match a specified regular expression with a string returned by a MatchEvaluator delegate. Additional parameters specify options that modify the matching operation and a time-out interval if no match is found.

Replace(String, String, Int32, Int32)

In a specified input substring, replaces a specified maximum number of strings that match a regular expression pattern with a specified replacement string.

Replace(String, String, String)

In a specified input string, replaces all strings that match a specified regular expression with a specified replacement string.

Replace(String, String, MatchEvaluator)

In a specified input string, replaces all strings that match a specified regular expression with a string returned by a MatchEvaluator delegate.

Replace(String, String, Int32)

In a specified input string, replaces a specified maximum number of strings that match a regular expression pattern with a specified replacement string.

Replace(String, MatchEvaluator)

In a specified input string, replaces all strings that match a specified regular expression with a string returned by a MatchEvaluator delegate.

Replace(String, String)

In a specified input string, replaces all strings that match a regular expression pattern with a specified replacement string.

Replace(String, MatchEvaluator, Int32)

In a specified input string, replaces a specified maximum number of strings that match a regular expression pattern with a string returned by a MatchEvaluator delegate.

Replace(String, String, String, RegexOptions)

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

In a specified input string, replaces all strings that match a specified regular expression with a specified replacement string. Specified options modify the matching operation.

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

Parameters

input
String

The string to search for a match.

pattern
String

The regular expression pattern to match.

replacement
String

The replacement string.

options
RegexOptions

A bitwise combination of the enumeration values that provide options for matching.

Returns

A new string that is identical to the input string, except that the replacement string takes the place of each matched string. If pattern is not matched in the current instance, the method returns the current instance unchanged.

Exceptions

A regular expression parsing error occurred.

input, pattern, or replacement is null.

options is not a valid bitwise combination of RegexOptions values.

A time-out occurred. For more information about time-outs, see the Remarks section.

Examples

The following example uses the Replace(String, String, String, RegexOptions) method to replace the local machine and drive names in a UNC path with a local file path. The regular expression uses the Environment.MachineName property to include the name of the local computer, and the Environment.GetLogicalDrives method to include the names of the logical drives. All regular expression string comparisons are case-insensitive. To run the example successfully, you should replace the literal string "MyMachine" with your local machine name.

using System;
using System.Text.RegularExpressions;

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

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

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

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

The regular expression pattern is defined by the following expression:

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

The following table shows how the regular expression pattern is interpreted.

Pattern Description
\\\\ Match two consecutive backslash (\) characters. Because the backslash character is interpreted as the escape character, each backslash must be escaped with another backslash.
+ Environment.MachineName + Match the string that is returned by the Environment.MachineName property.
(?:\.\w+)* Match the period (.) character followed by one or more word characters. This match can occur zero or more times. The matched subexpression is not captured.
\\ Match a backslash (\) character.
([" + driveNames + "]) Match the character class that consists of the individual drive letters. This match is the first captured subexpression.
\$ Match the literal dollar sign ($) character.

The replacement pattern $1 replaces the entire match with the first captured subexpression. That is, it replaces the UNC machine and drive name with the drive letter.

Remarks

The static Replace methods are equivalent to constructing a Regex object with the specified regular expression pattern and calling the instance method Replace.

The pattern parameter consists of regular expression language elements that symbolically describe the string to match. For more information about regular expressions, see .NET Regular Expressions and Regular Expression Language - Quick Reference. If you specify RightToLeft for the options parameter, the search for matches begins at the end of the input string and moves left; otherwise, the search begins at the start of the input string and moves right.

The replacement parameter specifies the string that is to replace each match in input. replacement can consist of any combination of literal text and substitutions. For example, the replacement pattern a*${test}b inserts the string "a*" followed by the substring that is matched by the test capturing group, if any, followed by the string "b". The * character is not recognized as a metacharacter within a replacement pattern.

Note

Substitutions are the only regular expression language elements that are recognized in a replacement pattern. All other regular expression language elements, including character escapes, are allowed in regular expression patterns only and are not recognized in replacement patterns.

The RegexMatchTimeoutException exception is thrown if the execution time of the replacement operation exceeds the time-out interval specified for the application domain in which the method is called. If no time-out is defined in the application domain's properties, or if the time-out value is Regex.InfiniteMatchTimeout, no exception is thrown.

Because the method returns input unchanged if there is no match, you can use the Object.ReferenceEquals method to determine whether the method has made any replacements to the input string.

Notes to Callers

This method times out after an interval that is equal to the default time-out value of the application domain in which it is called. If a time-out value has not been defined for the application domain, the value InfiniteMatchTimeout, which prevents the method from timing out, is used. The recommended static method for replacing a pattern match is Replace(String, String, String, RegexOptions, TimeSpan), which lets you set the time-out interval.

See also

Applies to

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

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

In a specified input string, replaces all strings that match a specified regular expression with a specified replacement string. Additional parameters specify options that modify the matching operation and a time-out interval if no match is found.

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

Parameters

input
String

The string to search for a match.

pattern
String

The regular expression pattern to match.

replacement
String

The replacement string.

options
RegexOptions

A bitwise combination of the enumeration values that provide options for matching.

matchTimeout
TimeSpan

A time-out interval, or InfiniteMatchTimeout to indicate that the method should not time out.

Returns

A new string that is identical to the input string, except that the replacement string takes the place of each matched string. If pattern is not matched in the current instance, the method returns the current instance unchanged.

Exceptions

A regular expression parsing error occurred.

input, pattern, or replacement is null.

options is not a valid bitwise combination of RegexOptions values.

-or-

matchTimeout is negative, zero, or greater than approximately 24 days.

A time-out occurred. For more information about time-outs, see the Remarks section.

Examples

The following example uses the Replace(String, String, String, RegexOptions, TimeSpan) method to replace the local machine and drive names in a UNC path with a local file path. The regular expression uses the Environment.MachineName property to include the name of the local computer and the Environment.GetLogicalDrives method to include the names of the logical drives. All regular expression string comparisons are case-insensitive, and any single replacement operation times out if a match cannot be found in 0.5 second. To run the example successfully, you should replace the literal string "MyMachine" with your local machine name.

using System;
using System.Text.RegularExpressions;

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

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

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

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

The regular expression pattern is defined by the following expression:

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

The following table shows how the regular expression pattern is interpreted.

Pattern Description
\\\\ Match two consecutive backslash (\) characters. Because the backslash character is interpreted as the escape character, each backslash must be escaped with another backslash.
+ Environment.MachineName + Match the string that is returned by the Environment.MachineName property.
(?:\.\w+)* Match the period (.) character followed by one or more word characters. This match can occur zero or more times. The matched subexpression is not captured.
\\ Match a backslash (\) character.
([" + driveNames + "]) Match the character class that consists of the individual drive letters. This match is the first captured subexpression.
\$ Match the literal dollar sign ($) character.

The replacement pattern $1 replaces the entire match with the first captured subexpression. That is, it replaces the UNC machine and drive name with the drive letter.

Remarks

The static Replace methods are equivalent to constructing a Regex object with the specified regular expression pattern and calling the instance method Replace.

The pattern parameter consists of regular expression language elements that symbolically describe the string to match. For more information about regular expressions, see .NET Regular Expressions and Regular Expression Language - Quick Reference. If you specify RightToLeft for the options parameter, the search for matches begins at the end of the input string and moves left; otherwise, the search begins at the start of the input string and moves right.

The replacement parameter specifies the string that is to replace each match in input. replacement can consist of any combination of literal text and substitutions. For example, the replacement pattern a*${test}b inserts the string "a*" followed by the substring that is matched by the test capturing group, if any, followed by the string "b". The * character is not recognized as a metacharacter within a replacement pattern.

Note

Substitutions are the only regular expression language elements that are recognized in a replacement pattern. All other regular expression language elements, including character escapes, are allowed in regular expression patterns only and are not recognized in replacement patterns.

The matchTimeout parameter specifies how long a pattern matching method should try to find a match before it times out. Setting a time-out interval prevents regular expressions that rely on excessive backtracking from appearing to stop responding when they process input that contains near matches. For more information, see Best Practices for Regular Expressions and Backtracking. If no match is found in that time interval, the method throws a RegexMatchTimeoutException exception. matchTimeout overrides any default time-out value defined for the application domain in which the method executes.

Because the method returns input unchanged if there is no match, you can use the Object.ReferenceEquals method to determine whether the method has made any replacements to the input string.

Notes to Callers

We recommend that you set the matchTimeout parameter to an appropriate value, such as two seconds. If you disable time-outs by specifying InfiniteMatchTimeout, the regular expression engine offers slightly better performance. However, you should disable time-outs only under the following conditions:

  • When the input processed by a regular expression is derived from a known and trusted source or consists of static text. This excludes text that has been dynamically input by users.

  • When the regular expression pattern has been thoroughly tested to ensure that it efficiently handles matches, non-matches, and near matches.

  • When the regular expression pattern contains no language elements that are known to cause excessive backtracking when processing a near match.

See also

Applies to

Replace(String, MatchEvaluator, Int32, Int32)

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

In a specified input substring, replaces a specified maximum number of strings that match a regular expression pattern with a string returned by a MatchEvaluator delegate.

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

Parameters

input
String

The string to search for a match.

evaluator
MatchEvaluator

A custom method that examines each match and returns either the original matched string or a replacement string.

count
Int32

The maximum number of times the replacement will occur.

startat
Int32

The character position in the input string where the search begins.

Returns

A new string that is identical to the input string, except that a replacement string takes the place of each matched string. If the regular expression pattern is not matched in the current instance, the method returns the current instance unchanged.

Exceptions

input or evaluator is null.

startat is less than zero or greater than the length of input.

A time-out occurred. For more information about time-outs, see the Remarks section.

Remarks

The Regex.Replace(String, MatchEvaluator, Int32, Int32) method is useful for replacing a regular expression match if any of the following conditions is true:

  • The replacement string cannot readily be specified by a regular expression replacement pattern.
  • The replacement string results from some processing done on the matched string.
  • The replacement string results from conditional processing.

The method is equivalent to calling the Regex.Matches(String, Int32) method and passing the first count Match objects in the returned MatchCollection collection to the evaluator delegate.

For more details about startat, see the Remarks section of Match(String, Int32).

The regular expression is the pattern defined by the constructor for the current Regex object.

The evaluator parameter is the delegate for a custom method that you define and that examines each match. The custom method must have the following signature to match the MatchEvaluator delegate.

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

Your custom method returns a string that replaces the matched input.

The RegexMatchTimeoutException exception is thrown if the execution time of the replacement operation exceeds the time-out interval specified by the Regex.Regex(String, RegexOptions, TimeSpan) constructor. If you do not set a time-out interval when you call the constructor, the exception is thrown if the operation exceeds any time-out value established for the application domain in which the Regex object is created. If no time-out is defined in the Regex constructor call or in the application domain's properties, or if the time-out value is Regex.InfiniteMatchTimeout, no exception is thrown

Because the method returns input unchanged if there is no match, you can use the Object.ReferenceEquals method to determine whether the method has made any replacements to the input string.

See also

Applies to

Replace(String, String, MatchEvaluator, RegexOptions)

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

In a specified input string, replaces all strings that match a specified regular expression with a string returned by a MatchEvaluator delegate. Specified options modify the matching operation.

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

Parameters

input
String

The string to search for a match.

pattern
String

The regular expression pattern to match.

evaluator
MatchEvaluator

A custom method that examines each match and returns either the original matched string or a replacement string.

options
RegexOptions

A bitwise combination of the enumeration values that provide options for matching.

Returns

A new string that is identical to the input string, except that a replacement string takes the place of each matched string. If pattern is not matched in the current instance, the method returns the current instance unchanged.

Exceptions

A regular expression parsing error occurred.

input, pattern, or evaluator is null.

options is not a valid bitwise combination of RegexOptions values.

A time-out occurred. For more information about time-outs, see the Remarks section.

Examples

The following example uses a regular expression to extract the individual words from a string, and then uses a MatchEvaluator delegate to call a method named WordScramble that scrambles the individual letters in the word. To do this, the WordScramble method creates an array that contains the characters in the match. It also creates a parallel array that it populates with random floating-point numbers. The arrays are sorted by calling the Array.Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>) method, and the sorted array is provided as an argument to a String class constructor. This newly created string is then returned by the WordScramble method. The regular expression pattern \w+ matches one or more word characters; the regular expression engine will continue to add characters to the match until it encounters a non-word character, such as a white-space character. The call to the Replace(String, String, MatchEvaluator, RegexOptions) method includes the RegexOptions.IgnorePatternWhitespace option so that the comment in the regular expression pattern \w+ # Matches all the characters in a word. is ignored by the regular expression engine.

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

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

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

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

Remarks

The Regex.Replace(String, String, MatchEvaluator, RegexOptions) method is useful for replacing a regular expression match in if any of the following conditions is true:

  • The replacement string cannot readily be specified by a regular expression replacement pattern.

  • The replacement string results from some processing done on the matched string.

  • The replacement string results from conditional processing.

The method is equivalent to calling the Regex.Matches(String, String, RegexOptions) method and passing each Match object in the returned MatchCollection collection to the evaluator delegate.

The pattern parameter consists of regular expression language elements that symbolically describe the string to match. For more information about regular expressions, see .NET Regular Expressions and Regular Expression Language - Quick Reference.

The evaluator parameter is the delegate for a custom method that you define and that examines each match. The custom method must have the following signature to match the MatchEvaluator delegate.

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

Your custom method returns a string that replaces the matched input.

If you specify RightToLeft for the options parameter, the search for matches begins at the end of the input string and moves left; otherwise, the search begins at the start of the input string and moves right.

The RegexMatchTimeoutException exception is thrown if the execution time of the replacement operation exceeds the time-out interval specified for the application domain in which the method is called. If no time-out is defined in the application domain's properties, or if the time-out value is Regex.InfiniteMatchTimeout, no exception is thrown.

Because the method returns input unchanged if there is no match, you can use the Object.ReferenceEquals method to determine whether the method has made any replacements to the input string.

See also

Applies to

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

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

In a specified input string, replaces all substrings that match a specified regular expression with a string returned by a MatchEvaluator delegate. Additional parameters specify options that modify the matching operation and a time-out interval if no match is found.

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

Parameters

input
String

The string to search for a match.

pattern
String

The regular expression pattern to match.

evaluator
MatchEvaluator

A custom method that examines each match and returns either the original matched string or a replacement string.

options
RegexOptions

A bitwise combination of enumeration values that provide options for matching.

matchTimeout
TimeSpan

A time-out interval, or InfiniteMatchTimeout to indicate that the method should not time out.

Returns

A new string that is identical to the input string, except that the replacement string takes the place of each matched string. If pattern is not matched in the current instance, the method returns the current instance unchanged.

Exceptions

A regular expression parsing error occurred.

input, pattern, or evaluator is null.

options is not a valid bitwise combination of RegexOptions values.

-or-

matchTimeout is negative, zero, or greater than approximately 24 days.

A time-out occurred. For more information about time-outs, see the Remarks section.

Examples

The following example uses a regular expression to extract the individual words from a string, and then uses a MatchEvaluator delegate to call a method named WordScramble that scrambles the individual letters in the word. To do this, the WordScramble method creates an array that contains the characters in the match. It also creates a parallel array that it populates with random floating-point numbers. The arrays are sorted by calling the Array.Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>) method, and the sorted array is provided as an argument to a String class constructor. This newly created string is then returned by the WordScramble method. The regular expression pattern \w+ matches one or more word characters; the regular expression engine will continue to add characters to the match until it encounters a non-word character, such as a white-space character. The call to the Replace(String, String, MatchEvaluator, RegexOptions) method includes the RegexOptions.IgnorePatternWhitespace option so that the comment in the regular expression pattern \w+ # Matches all the characters in a word. is ignored by the regular expression engine.

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

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

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

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

Remarks

The Regex.Replace(String, String, MatchEvaluator, RegexOptions) method is useful for replacing a regular expression match if any of the following conditions is true:

  • If the replacement string cannot readily be specified by a regular expression replacement pattern.

  • If the replacement string results from some processing performed on the matched string.

  • If the replacement string results from conditional processing.

The method is equivalent to calling the Regex.Matches(String, String, RegexOptions) method and passing each Match object in the returned MatchCollection collection to the evaluator delegate.

The pattern parameter consists of regular expression language elements that symbolically describe the string to match. For more information about regular expressions, see .NET Regular Expressions and Regular Expression Language - Quick Reference.

The evaluator parameter is the delegate for a custom method that you define and that examines each match. The custom method must have the following signature to match the MatchEvaluator delegate.

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

Your custom method returns a string that replaces the matched input.

If you specify RightToLeft for the options parameter, the search for matches begins at the end of the input string and moves left; otherwise, the search begins at the start of the input string and moves right.

The matchTimeout parameter specifies how long a pattern matching method should try to find a match before it times out. Setting a time-out interval prevents regular expressions that rely on excessive backtracking from appearing to "stop responding when they process input that contains near matches. For more information, see Best Practices for Regular Expressions and Backtracking. If no match is found in that time interval, the method throws a RegexMatchTimeoutException exception. matchTimeout overrides any default time-out value defined for the application domain in which the method executes.

Because the method returns input unchanged if there is no match, you can use the Object.ReferenceEquals method to determine whether the method has made any replacements to the input string.

Notes to Callers

We recommend that you set the matchTimeout parameter to an appropriate value, such as two seconds. If you disable time-outs by specifying InfiniteMatchTimeout, the regular expression engine offers slightly better performance. However, you should disable time-outs only under the following conditions:

  • When the input processed by a regular expression is derived from a known and trusted source or consists of static text. This excludes text that has been dynamically input by users.

  • When the regular expression pattern has been thoroughly tested to ensure that it efficiently handles matches, non-matches, and near matches.

  • When the regular expression pattern contains no language elements that are known to cause excessive backtracking when processing a near match.

See also

Applies to

Replace(String, String, Int32, Int32)

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

In a specified input substring, replaces a specified maximum number of strings that match a regular expression pattern with a specified replacement string.

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

Parameters

input
String

The string to search for a match.

replacement
String

The replacement string.

count
Int32

Maximum number of times the replacement can occur.

startat
Int32

The character position in the input string where the search begins.

Returns

A new string that is identical to the input string, except that the replacement string takes the place of each matched string. If the regular expression pattern is not matched in the current instance, the method returns the current instance unchanged.

Exceptions

input or replacement is null.

startat is less than zero or greater than the length of input.

A time-out occurred. For more information about time-outs, see the Remarks section.

Examples

The following example double-spaces all but the first line of a string. It defines a regular expression pattern, ^.*$, that matches a line of text, calls the Match(String) method to match the first line of the string, and uses the Match.Index and Match.Count properties to determine the starting position of the second line.

using System;
using System.Text.RegularExpressions;

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

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

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

The regular expression pattern ^.*$ is defined as shown in the following table.

Pattern Description
^ Match the start of a line. (Note that the Regex object was instantiated by using the RegexOptions.Multiline option; otherwise, this character class would only match the beginning of the input string.)
.* Match any character zero or more times.
$ Match the end of a line. (Note that the Regex object was instantiated by using the RegexOptions.Multiline option; otherwise, this character class would only match the beginning of the input string.)

The replacement string (vbCrLf + "$&" in Visual Basic, "\n$&" in C#) adds a new line before the matched string. Note that \n in the C# example is interpreted as the newline character by the C# compiler; it does not represent a regular expression character escape.

Remarks

The search for matches starts in the input string at the position specified by the startat parameter. The regular expression is the pattern defined by the constructor for the current Regex object. If count is negative, replacements continue to the end of the string. If count exceeds the number of matches, all matches are replaced.

For more details about startat, see the Remarks section of Match(String, Int32).

The replacement parameter specifies the string that is to replace each match in input. replacement can consist of any combination of literal text and substitutions. For example, the replacement pattern a*${test}b inserts the string "a*" followed by the substring that is matched by the test capturing group, if any, followed by the string "b". The * character is not recognized as a metacharacter within a replacement pattern.

Note

Substitutions are the only regular expression language elements that are recognized in a replacement pattern. All other regular expression language elements, including character escapes, are allowed in regular expression patterns only and are not recognized in replacement patterns.

The RegexMatchTimeoutException exception is thrown if the execution time of the replacement operation exceeds the time-out interval specified by the Regex.Regex(String, RegexOptions, TimeSpan) constructor. If you do not set a time-out interval when you call the constructor, the exception is thrown if the operation exceeds any time-out value established for the application domain in which the Regex object is created. If no time-out is defined in the Regex constructor call or in the application domain's properties, or if the time-out value is Regex.InfiniteMatchTimeout, no exception is thrown

Because the method returns input unchanged if there is no match, you can use the Object.ReferenceEquals method to determine whether the method has made any replacements to the input string.

See also

Applies to

Replace(String, String, String)

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

In a specified input string, replaces all strings that match a specified regular expression with a specified replacement string.

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

Parameters

input
String

The string to search for a match.

pattern
String

The regular expression pattern to match.

replacement
String

The replacement string.

Returns

A new string that is identical to the input string, except that the replacement string takes the place of each matched string. If pattern is not matched in the current instance, the method returns the current instance unchanged.

Exceptions

A regular expression parsing error occurred.

input, pattern, or replacement is null.

A time-out occurred. For more information about time-outs, see the Remarks section.

Examples

The following example defines a regular expression, \s+, that matches one or more white-space characters. The replacement string, " ", replaces them with a single space character.

using System;
using System.Text.RegularExpressions;

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

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

The following example uses the Replace(String, String, String) method to replace the local machine and drive names in a UNC path with a local file path. The regular expression uses the Environment.MachineName property to include the name of the local computer, and the Environment.GetLogicalDrives method to include the names of the logical drives. To run the example successfully, you should replace the literal string "MyMachine" with your local machine name.

using System;
using System.Text.RegularExpressions;

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

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

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

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

The regular expression pattern is defined by the following expression:

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

The following table shows how the regular expression pattern is interpreted.

Pattern Description
\\\\ Match two consecutive backslash (\) characters. Because the backslash character is interpreted as the escape character, each backslash must be escaped with another backslash.
(?i:" + Environment.MachineName + ") Perform a case-insensitive match of the string that is returned by the Environment.MachineName property.
(?:\.\w+)* Match the period (.) character followed by one or more word characters. This match can occur zero or more times. The matched subexpression is not captured.
\\ Match a backslash (\) character.
((?i:[" + driveNames + "])) Perform a case-insensitive match of the character class that consists of the individual drive letters. This match is the first captured subexpression.
\$ Match the literal dollar sign ($) character.

The replacement pattern $1 replaces the entire match with the first captured subexpression. That is, it replaces the UNC machine and drive name with the drive letter.

Remarks

The static Replace methods are equivalent to constructing a Regex object with the specified regular expression pattern and calling the instance method Replace.

The pattern parameter consists of regular expression language elements that symbolically describe the string to match. For more information about regular expressions, see .NET Regular Expressions and Regular Expression Language - Quick Reference. The search for matches starts at the beginning of the input string.

The replacement parameter specifies the string that is to replace each match in input. replacement can consist of any combination of literal text and substitutions. For example, the replacement pattern a*${test}b inserts the string "a*" followed by the substring that is matched by the test capturing group, if any, followed by the string "b". The * character is not recognized as a metacharacter within a replacement pattern.

Note

Substitutions are the only regular expression language elements that are recognized in a replacement pattern. All other regular expression language elements, including character escapes, are allowed in regular expression patterns only and are not recognized in replacement patterns.

The RegexMatchTimeoutException exception is thrown if the execution time of the replacement operation exceeds the time-out interval specified for the application domain in which the method is called. If no time-out is defined in the application domain's properties, or if the time-out value is Regex.InfiniteMatchTimeout, no exception is thrown.

Because the method returns input unchanged if there is no match, you can use the Object.ReferenceEquals method to determine whether the method has made any replacements to the input string.

Notes to Callers

This method times out after an interval that is equal to the default time-out value of the application domain in which it is called. If a time-out value has not been defined for the application domain, the value InfiniteMatchTimeout, which prevents the method from timing out, is used. The recommended static method for replacing a pattern match is Replace(String, String, String, RegexOptions, TimeSpan), which lets you set the time-out interval.

See also

Applies to

Replace(String, String, MatchEvaluator)

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

In a specified input string, replaces all strings that match a specified regular expression with a string returned by a MatchEvaluator delegate.

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

Parameters

input
String

The string to search for a match.

pattern
String

The regular expression pattern to match.

evaluator
MatchEvaluator

A custom method that examines each match and returns either the original matched string or a replacement string.

Returns

A new string that is identical to the input string, except that a replacement string takes the place of each matched string. If pattern is not matched in the current instance, the method returns the current instance unchanged.

Exceptions

A regular expression parsing error occurred.

input, pattern, or evaluator is null.

A time-out occurred. For more information about time-outs, see the Remarks section.

Examples

The following example uses a regular expression to extract the individual words from a string, and then uses a MatchEvaluator delegate to call a method named WordScramble that scrambles the individual letters in the word. To do this, the WordScramble method creates an array that contains the characters in the match. It also creates a parallel array that it populates with random floating-point numbers. The arrays are sorted by calling the Array.Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>) method, and the sorted array is provided as an argument to a String class constructor. This newly created string is then returned by the WordScramble method. The regular expression pattern \w+ matches one or more word characters; the regular expression engine will continue to add characters to the match until it encounters a non-word character, such as a white-space character.

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

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

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

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

Remarks

The Regex.Replace(String, String, MatchEvaluator) method is useful for replacing a regular expression match if any of the following conditions is true:

  • The replacement string cannot readily be specified by a regular expression replacement pattern.

  • The replacement string results from some processing done on the matched string.

  • The replacement string results from conditional processing.

The method is equivalent to calling the Regex.Matches(String, String) method and passing each Match object in the returned MatchCollection collection to the evaluator delegate.

The pattern parameter consists of regular expression language elements that symbolically describe the string to match. For more information about regular expressions, see .NET Regular Expressions and Regular Expression Language - Quick Reference.

The evaluator parameter is the delegate for a custom method that you define and that examines each match. The custom method must have the following signature to match the MatchEvaluator delegate.

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

Your custom method returns a string that replaces the matched input.

The RegexMatchTimeoutException exception is thrown if the execution time of the replacement operation exceeds the time-out interval specified for the application domain in which the method is called. If no time-out is defined in the application domain's properties, or if the time-out value is Regex.InfiniteMatchTimeout, no exception is thrown.

Because the method returns input unchanged if there is no match, you can use the Object.ReferenceEquals method to determine whether the method has made any replacements to the input string.

Notes to Callers

This method times out after an interval that is equal to the default time-out value of the application domain in which it is called. If a time-out value has not been defined for the application domain, the value InfiniteMatchTimeout, which prevents the method from timing out, is used. The recommended static method for evaluating and replacing a pattern match is Replace(String, String, MatchEvaluator, RegexOptions, TimeSpan), which lets you set the time-out interval.

See also

Applies to

Replace(String, String, Int32)

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

In a specified input string, replaces a specified maximum number of strings that match a regular expression pattern with a specified replacement string.

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

Parameters

input
String

The string to search for a match.

replacement
String

The replacement string.

count
Int32

The maximum number of times the replacement can occur.

Returns

A new string that is identical to the input string, except that the replacement string takes the place of each matched string. If the regular expression pattern is not matched in the current instance, the method returns the current instance unchanged.

Exceptions

input or replacement is null.

A time-out occurred. For more information about time-outs, see the Remarks section.

Examples

The following example replaces the first five occurrences of duplicated characters with a single character. The regular expression pattern (\w)\1 matches consecutive occurrences of a single character and assigns the first occurrence to the first capturing group. The replacement pattern $1 replaces the entire match with the first captured group.

using System;
using System.Text.RegularExpressions;

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

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

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

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

Remarks

The search for matches starts at the beginning of the input string. The regular expression is the pattern that is defined by the constructor for the current Regex object. If count is negative, replacements continue to the end of the string. If count exceeds the number of matches, all matches are replaced.

The replacement parameter specifies the string that is to replace the first count matches in input. replacement can consist of any combination of literal text and substitutions. For example, the replacement pattern a*${test}b inserts the string "a*" followed by the substring that is matched by the test capturing group, if any, followed by the string "b". The * character is not recognized as a metacharacter within a replacement pattern.

Note

Substitutions are the only regular expression language elements that are recognized in a replacement pattern. All other regular expression language elements, including character escapes, are allowed in regular expression patterns only and are not recognized in replacement patterns.

The RegexMatchTimeoutException exception is thrown if the execution time of the replacement operation exceeds the time-out interval specified by the Regex.Regex(String, RegexOptions, TimeSpan) constructor. If you do not set a time-out interval when you call the constructor, the exception is thrown if the operation exceeds any time-out value established for the application domain in which the Regex object is created. If no time-out is defined in the Regex constructor call or in the application domain's properties, or if the time-out value is Regex.InfiniteMatchTimeout, no exception is thrown

Because the method returns input unchanged if there is no match, you can use the Object.ReferenceEquals method to determine whether the method has made any replacements to the input string.

See also

Applies to

Replace(String, MatchEvaluator)

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

In a specified input string, replaces all strings that match a specified regular expression with a string returned by a MatchEvaluator delegate.

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

Parameters

input
String

The string to search for a match.

evaluator
MatchEvaluator

A custom method that examines each match and returns either the original matched string or a replacement string.

Returns

A new string that is identical to the input string, except that a replacement string takes the place of each matched string. If the regular expression pattern is not matched in the current instance, the method returns the current instance unchanged.

Exceptions

input or evaluator is null.

A time-out occurred. For more information about time-outs, see the Remarks section.

Examples

The following code example displays an original string, matches each word in the original string, converts the first character of each match to uppercase, then displays the converted string.

using System;
using System.Text.RegularExpressions;

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

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

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

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

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

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

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

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

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

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

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

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

Remarks

The Regex.Replace(String, MatchEvaluator) method is useful for replacing a regular expression match if any of the following conditions is true:

  • The replacement string cannot readily be specified by a regular expression replacement pattern.

  • The replacement string results from some processing done on the matched string.

  • The replacement string results from conditional processing.

The method is equivalent to calling the Regex.Matches(String) method and passing each Match object in the returned MatchCollection collection to the evaluator delegate.

The regular expression is the pattern defined by the constructor for the current Regex object.

The evaluator parameter is the delegate for a custom method that you define and that examines each match. The custom method must have the following signature to match the MatchEvaluator delegate.

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

Your custom method returns a string that replaces the matched input.

The RegexMatchTimeoutException exception is thrown if the execution time of the replacement operation exceeds the time-out interval specified by the Regex.Regex(String, RegexOptions, TimeSpan) constructor. If you do not set a time-out interval when you call the constructor, the exception is thrown if the operation exceeds any time-out value established for the application domain in which the Regex object is created. If no time-out is defined in the Regex constructor call or in the application domain's properties, or if the time-out value is Regex.InfiniteMatchTimeout, no exception is thrown

Because the method returns input unchanged if there is no match, you can use the Object.ReferenceEquals method to determine whether the method has made any replacements to the input string.

See also

Applies to

Replace(String, String)

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

In a specified input string, replaces all strings that match a regular expression pattern with a specified replacement string.

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

Parameters

input
String

The string to search for a match.

replacement
String

The replacement string.

Returns

A new string that is identical to the input string, except that the replacement string takes the place of each matched string. If the regular expression pattern is not matched in the current instance, the method returns the current instance unchanged.

Exceptions

input or replacement is null.

A time-out occurred. For more information about time-outs, see the Remarks section.

Examples

The following example defines a regular expression, \s+, that matches one or more white-space characters. The replacement string, " ", replaces them with a single space character.

using System;
using System.Text.RegularExpressions;

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

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

The following example defines a regular expression, (\p{Sc}\s?)?(\d+\.?((?<=\.)\d+)?)(?(1)|\s?\p{Sc})?, and a replacement pattern, $2, that removes either a leading or a trailing currency symbol from a numeric value.

using System;
using System.Text.RegularExpressions;

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

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

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

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

The regular expression is interpreted as shown in the following table.

Pattern Description
\p{Sc} Match a currency symbol. {Sc} denotes any character that is a member of the Unicode Symbol, Currency category.
\s? Match zero or one white-space character.
(\p{Sc}\s?)? Match zero or one occurrence of the combination of a currency symbol followed by zero or one white-space character. This is the first capturing group.
\d+ Match one or more decimal digits.
\.? Match zero or one occurrence of a period (used as a decimal separator character).
((?<=\.)\d+)? If a period is the previous character, match one or more decimal digits. This pattern can be matched either zero or one time.
(\d+\.?((?<=\.)\d+)?) Match the pattern of one or more decimal digits followed by an optional period and additional decimal digits. This is the second capturing group. The call to the Replace(String, String) method replaces the entire match with the value of this captured group.
(?(1)|\s?\p{Sc})? If the first captured group exists, match an empty string. Otherwise, match zero or one white-space character followed by a currency symbol.

Remarks

The search for matches starts at the beginning of the input string. The regular expression is the pattern defined by the constructor for the current Regex object.

The replacement parameter specifies the string that is to replace each match in input. replacement can consist of any combination of literal text and substitutions. For example, the replacement pattern a*${test}b inserts the string "a*" followed by the substring that is matched by the test capturing group, if any, followed by the string "b". The * character is not recognized as a metacharacter within a replacement pattern.

Note

Substitutions are the only regular expression language elements that are recognized in a replacement pattern. All other regular expression language elements, including character escapes, are allowed in regular expression patterns only and are not recognized in replacement patterns.

The RegexMatchTimeoutException exception is thrown if the execution time of the replacement operation exceeds the time-out interval specified by the Regex.Regex(String, RegexOptions, TimeSpan) constructor. If you do not set a time-out interval when you call the constructor, the exception is thrown if the operation exceeds any time-out value established for the application domain in which the Regex object is created. If no time-out is defined in the Regex constructor call or in the application domain's properties, or if the time-out value is Regex.InfiniteMatchTimeout, no exception is thrown

Because the method returns input unchanged if there is no match, you can use the Object.ReferenceEquals method to determine whether the method has made any replacements to the input string.

See also

Applies to

Replace(String, MatchEvaluator, Int32)

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

In a specified input string, replaces a specified maximum number of strings that match a regular expression pattern with a string returned by a MatchEvaluator delegate.

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

Parameters

input
String

The string to search for a match.

evaluator
MatchEvaluator

A custom method that examines each match and returns either the original matched string or a replacement string.

count
Int32

The maximum number of times the replacement will occur.

Returns

A new string that is identical to the input string, except that a replacement string takes the place of each matched string. If the regular expression pattern is not matched in the current instance, the method returns the current instance unchanged.

Exceptions

input or evaluator is null.

A time-out occurred. For more information about time-outs, see the Remarks section.

Examples

The following example uses a regular expression to deliberately misspell half of the words in a list. It uses the regular expression \w*(ie|ei)\w* to match words that include the characters "ie" or "ei". It passes the first half of the matching words to the ReverseLetter method, which, in turn, uses the Replace(String, String, String, RegexOptions) method to reverse "i" and "e" in the matched string. The remaining words remain unchanged.

using System;
using System.Text.RegularExpressions;

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

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

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

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

The regular expression \w*(ie|ei)\w* is defined as shown in the following table.

Pattern Description
\w* Match zero or more word characters.
(ie|ei) Match either "ie" or "ei".
\w* Match zero or more word characters.

The regular expression pattern ([ie])([ie]) in the ReverseLetter method matches the first "i" or "e" in the diphthong "ie" or "ei" and assigns the letter to the first capturing group. It matches the second "i" or "e" and assigns the letter to the second capturing group. The two characters are then reversed by calling the Replace(String, String, String) method with the replacement pattern $2$1.

Remarks

The Regex.Replace(String, MatchEvaluator, Int32) method is useful for replacing a regular expression match if any of the following conditions is true:

  • The replacement string cannot readily be specified by a regular expression replacement pattern.

  • The replacement string results from some processing done on the matched string.

  • The replacement string results from conditional processing.

The method is equivalent to calling the Regex.Matches(String) method and passing the first count Match objects in the returned MatchCollection collection to the evaluator delegate.

The regular expression is the pattern defined by the constructor for the current Regex object.

The evaluator parameter is the delegate for a custom method that you define and that examines each match. The custom method must have the following signature to match the MatchEvaluator delegate.

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

Your custom method returns a string that replaces the matched input.

The RegexMatchTimeoutException exception is thrown if the execution time of the replacement operation exceeds the time-out interval specified by the Regex.Regex(String, RegexOptions, TimeSpan) constructor. If you do not set a time-out interval when you call the constructor, the exception is thrown if the operation exceeds any time-out value established for the application domain in which the Regex object is created. If no time-out is defined in the Regex constructor call or in the application domain's properties, or if the time-out value is Regex.InfiniteMatchTimeout, no exception is thrown

Because the method returns input unchanged if there is no match, you can use the Object.ReferenceEquals method to determine whether the method has made any replacements to the input string.

See also

Applies to