Updated: May 2009
Within a specified input string, replaces all strings that match a specified regular expression with a specified replacement string.
Namespace:
System.Text.RegularExpressions
Assembly:
System (in System.dll)
Visual Basic (Declaration)
Public Shared Function Replace ( _
input As String, _
pattern As String, _
replacement As String _
) As String
Dim input As String
Dim pattern As String
Dim replacement As String
Dim returnValue As String
returnValue = Regex.Replace(input, _
pattern, replacement)
public static string Replace(
string input,
string pattern,
string replacement
)
public:
static String^ Replace(
String^ input,
String^ pattern,
String^ replacement
)
public static function Replace(
input : String,
pattern : String,
replacement : String
) : String
Return Value
Type:
System..::.StringA new string that is identical to the input string, except that a replacement string takes the place of each matched string.
| Exception | Condition |
|---|
| ArgumentException | A regular expression parsing error has occurred. |
| ArgumentNullException |
input is nullNothingnullptra null reference (Nothing in Visual Basic). -or-
pattern is nullNothingnullptra null reference (Nothing in Visual Basic). -or-
replacement is nullNothingnullptra null reference (Nothing in Visual Basic). |
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 various 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 Elements. The search for matches starts at the beginning of the input parameter string.
Substitutions are allowed only within a replacement pattern. For similar functionality within a regular expression, use a backreference such as \1.
Character escapes and substitutions are the only special constructs recognized in a replacement pattern. All other syntactic constructs are allowed in regular expressions only and not recognized in replacement patterns. For example, the replacement pattern a*${test}b inserts the string "a*" followed by the substring 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. Similarly, $-patterns are not recognized within a regular expression matching pattern. Within a regular expression, $ denotes the end of the string. Other examples are: $123 substitutes the last substring matched by group number 123 (decimal), and ${name} substitutes the last substring matched by a (?<name>) group.
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 in the regular expression, and the Environment..::.GetLogicalDrives method to include the names of the logical drives.
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 = "["
For Each drive As String In drives
driveNames += drive.Substring(0,1)
Next
driveNames += "]"
' 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
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 = "[";
foreach (string drive in drives)
driveNames += drive.Substring(0,1);
driveNames += "]";
// 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
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 lettters. This match is the first captured subexpression. |
\$
| Match the literal dollar sign ($) character. |
Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC, Xbox 360, Zune
The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
.NET Framework
Supported in: 3.5, 3.0, 2.0, 1.1, 1.0
.NET Compact Framework
Supported in: 3.5, 2.0, 1.0
XNA Framework
Supported in: 3.0, 2.0, 1.0
Reference
Other Resources
Date | History | Reason |
|---|
May 2009
| Added an example. |
Customer feedback.
|