Regex.Escape
changes certain character sequences. It converts user-specified strings into escaped strings to match in a regular expression.
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.
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.
string
"\123."Regex.Escape
and becomes "\\123." So another backslash was added with Escape.Regex.Replace
method is called with the escaped value and replaces the pattern "\\123."using System; using System.Text.RegularExpressions; class Program { static void Main() { // User specified to remove this string. string value1 = @"\123"; // Escape the input. value1 = Regex.Escape(value1); // Write the escaped input. Console.WriteLine(value1); // 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. Console.WriteLine(output1); } }\\123 This is a string
This program first calls the Regex.Unescape
method on the string
literal "\\n." This is an escaped backslash "\\" and an "n."
using System; using System.Text.RegularExpressions; class Program { 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"); Console.WriteLine(result); // Unescape again to get an actual newline. result = Regex.Unescape(result); Console.WriteLine(result == "\n"); } }\n True
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.
Why would you ever want to use the Regex.Unescape
method? With Unescape we can make a string
more readable. It could be displayed.
string
that is meant to be used as a regular expression pattern, but you want to display its raw characters in a UI.Regex.Unescape
to visualize the original representation of the characters, not the escaped representation.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
.