Regex.Replace Method (String, String, String, RegexOptions, TimeSpan)

.NET Framework (current version)

The .NET API Reference documentation has a new home. Visit the .NET API Browser on to see the new experience.

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.

Namespace:   System.Text.RegularExpressions
Assembly:  System (in System.dll)

public static string Replace(
	string input,
	string pattern,
	string replacement,
	RegexOptions options,
	TimeSpan matchTimeout


Type: System.String

The string to search for a match.

Type: System.String

The regular expression pattern to match.

Type: System.String

The replacement string.

Type: System.Text.RegularExpressions.RegexOptions

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

Type: System.TimeSpan

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

Return Value

Type: System.String

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.

Exception Condition

A regular expression parsing error occurred.


input, pattern, or replacement is null.


options is not a valid bitwise combination of RegexOptions values.


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


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

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 Framework 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.


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 in the .NET Framework and Backtracking in Regular Expressions. 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 Regex.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.

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 = { @"\\\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, 
            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.");
               Console.WriteLine("Original string: " + uncPath);
// The example displays the following output if run on a machine whose name is
// MyMachine:
//    Input string: \\\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.




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.


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.

Universal Windows Platform
Available since 8
.NET Framework
Available since 4.5
Portable Class Library
Supported in: portable .NET platforms
Windows Phone Silverlight
Available since 8.0
Windows Phone
Available since 8.1
Return to top