After escaping, the patterns can be used—we can load Regex patterns from user input this way. With Unescape, also part of the Regex class, we reverse the Escape operation.
Escape. Regex.Escape is a static method that receives a string. Internally the Escape method allocates a new string containing the escaped character sequence and returns its reference.
Info Value 1 is the input that the user specifies. The user in this example specified the string "\123."
Then This value is then escaped with Regex.Escape and becomes "\\123." So another backslash was added with Escape.
Finally The Regex.Replace method is called with the escaped value and replaces the pattern "\\123."
static void Main()
// User specified to remove this string.
string value1 = @"\123";
// Escape the input.
value1 = Regex.Escape(value1);
// Write the escaped input.
// The string we are changing.
string input1 = @"This is\123a string";
// Remove the user-specified pattern.
string output1 = Regex.Replace(input1, value1, "");
// Write the output.
}(The backslash character was replaced.)
This isa string
Unescape. This program first calls the Regex.Unescape method on the string literal "\\n." This is an escaped backslash "\\" and an "n."
Detail The Unescape method transforms the escaped backslash into a regular backslash "\."
Then The method transforms the escaped newline sequence (the two characters "\n") into a real newline.
static void Main()
// You were using a Regex that matches the literal \n.// With Unescape, you can see the exact text that would be matched.
string result = Regex.Unescape(@"\\n");
// Unescape again to get an actual newline.
result = Regex.Unescape(result);
Console.WriteLine(result == "\n");
Discussion, Escape. The Regex.Escape method has many possible uses. Because you can always escape strings in the source code that you type in, you will not need to use it in most programs.
Tip If your program retrieves external input, you can use Escape to eliminate the chance that characters will be incorrectly used.
Discussion, Unescape. Why would you ever want to use the Regex.Unescape method? With Unescape we can make a string more readable. It could be displayed.
Info You may have a string that is meant to be used as a regular expression pattern, but you want to display its raw characters in a UI.
And You could use Regex.Unescape to visualize the original representation of the characters, not the escaped representation.
A summary. We used Regex.Escape. This is a powerful static method that can be useful when preparing dynamic input for use in a regular expression method such as Replace or Split.